# [LeetCode] 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 题目讲解汇总(持续更新中...)

posted @ 2016-02-29 01:19  Grandyang  阅读(11555)  评论(7编辑  收藏  举报