294. Flip Game II
Difficulty: Medium
Topics: Backtracking, Minimax
Similar Questions:
Problem:
You are playing the following Flip Game with your friend: Given a string that contains only these two characters: +
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.
Write a function to determine if the starting player can guarantee a win.
Example:
Input:s = "++++"
Output: true Explanation: The starting player can guarantee a win by flipping the middle"++"
to become"+--+"
.
Follow up:
Derive your algorithm's runtime complexity.
Solutions:
class Solution {
public:
bool canWin(string s) {
unordered_map<string, bool> cache;
return helper(s, cache);
}
private:
bool helper(string& s, unordered_map<string, bool>& cache) {
if (cache.count(s) > 0) return cache[s];
for (int i = 0; i < (int)s.length() - 1; ++i) {
if (s[i] == '+' && s[i+1] == '+') {
s[i] = '-';
s[i+1] = '-';
auto ret = (!helper(s, cache));
s[i + 1] = '+';
s[i] = '+';
if (ret == true) { // it is wrong to return result intermediately without set s back!
cache[s] = ret;
return true;
}
}
}
cache[s] = false;
return false;
}
};