File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 282
282
291|[ Word Pattern II] ( ./solutions/0291-word-pattern-ii.js ) |Medium|
283
283
292|[ Nim Game] ( ./solutions/0292-nim-game.js ) |Easy|
284
284
293|[ Flip Game] ( ./solutions/0293-flip-game.js ) |Easy|
285
+ 294|[ Flip Game II] ( ./solutions/0294-flip-game-ii.js ) |Medium|
285
286
295|[ Find Median from Data Stream] ( ./solutions/0295-find-median-from-data-stream.js ) |Hard|
286
287
297|[ Serialize and Deserialize Binary Tree] ( ./solutions/0297-serialize-and-deserialize-binary-tree.js ) |Hard|
287
288
299|[ Bulls and Cows] ( ./solutions/0299-bulls-and-cows.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 294. Flip Game II
3
+ * https://leetcode.com/problems/flip-game-ii/
4
+ * Difficulty: Medium
5
+ *
6
+ * You are playing a Flip Game with your friend.
7
+ *
8
+ * You are given a string currentState that contains only '+' and '-'. You and your friend take
9
+ * turns to flip two consecutive "++" into "--". The game ends when a person can no longer make
10
+ * a move, and therefore the other person will be the winner.
11
+ *
12
+ * Return true if the starting player can guarantee a win, and false otherwise.
13
+ */
14
+
15
+ /**
16
+ * @param {string } currentState
17
+ * @return {boolean }
18
+ */
19
+ var canWin = function ( currentState ) {
20
+ const map = new Map ( ) ;
21
+
22
+ return canWinFrom ( currentState ) ;
23
+
24
+ function canWinFrom ( state ) {
25
+ if ( map . has ( state ) ) return map . get ( state ) ;
26
+
27
+ for ( let i = 0 ; i < state . length - 1 ; i ++ ) {
28
+ if ( state [ i ] === '+' && state [ i + 1 ] === '+' ) {
29
+ const nextState = state . slice ( 0 , i ) + '--' + state . slice ( i + 2 ) ;
30
+ if ( ! canWinFrom ( nextState ) ) {
31
+ map . set ( state , true ) ;
32
+ return true ;
33
+ }
34
+ }
35
+ }
36
+
37
+ map . set ( state , false ) ;
38
+ return false ;
39
+ }
40
+ } ;
You can’t perform that action at this time.
0 commit comments