# 294. Flip Game II

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 "+--+".
``````

``````class Solution {
public:
bool canWin(string s) {
for (int i = 1; i < s.size(); ++i) {
if (s[i] == '+' && s[i - 1] == '+' && !canWin(s.substr(0, i - 1) + "--" + s.substr(i + 1))) {
return true;
}
}
return false;
}
};
``````

``````class Solution {
public:
bool canWin(string s) {
for (int i = -1; (i = s.find("++", i + 1)) >= 0;) {
if (!canWin(s.substr(0, i) + "--" + s.substr(i + 2))) {
return true;
}
}
return false;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/294

Flip Game

Guess Number Higher or Lower II

Can I Win

https://leetcode.com/problems/flip-game-ii/

https://leetcode.com/problems/flip-game-ii/discuss/74033/4-line-Java-Solution

https://leetcode.com/problems/flip-game-ii/discuss/74010/Short-Java-and-Ruby

https://leetcode.com/problems/flip-game-ii/discuss/73962/Share-my-Java-backtracking-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation