-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0294-flip-game-ii.js
More file actions
40 lines (35 loc) · 1.05 KB
/
0294-flip-game-ii.js
File metadata and controls
40 lines (35 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 294. Flip Game II
* https://leetcode.com/problems/flip-game-ii/
* Difficulty: Medium
*
* You are playing a Flip Game with your friend.
*
* You are given a string currentState that contains only '+' and '-'. You and your friend take
* turns to flip two consecutive "++" into "--". The game ends when a person can no longer make
* a move, and therefore the other person will be the winner.
*
* Return true if the starting player can guarantee a win, and false otherwise.
*/
/**
* @param {string} currentState
* @return {boolean}
*/
var canWin = function(currentState) {
const map = new Map();
return canWinFrom(currentState);
function canWinFrom(state) {
if (map.has(state)) return map.get(state);
for (let i = 0; i < state.length - 1; i++) {
if (state[i] === '+' && state[i + 1] === '+') {
const nextState = state.slice(0, i) + '--' + state.slice(i + 2);
if (!canWinFrom(nextState)) {
map.set(state, true);
return true;
}
}
}
map.set(state, false);
return false;
}
};