294. Flip Game II
方法1: backtracking
思路:
每次都穷举当前能翻转的所有位置,并递归询问对手是否会输。递归的终止条件是对任何一个人而言,自己没有可以移动的“++”就return false。循环的返回条件则是:有可以flip的“++”,并且我flip之后对方的递归会返回false。
class Solution {
public:
bool canWin(string s) {
for (int i = 1; i < s.size(); i++){
if (s[i - 1] == '+' && s[i] == '+'){
string next = s.substr(0, i - 1) + "--" + s.substr(i + 1);
if (!canWin(next)){
return true;
}
}
}
return false;
}
};
方法2: backtracking + memoize
小榕流光: https://blog.youkuaiyun.com/qq508618087/article/details/50935046
思路:
和上面的一样,但是用一个hash记住每次recursion 的结果。
class Solution {
public:
bool canWin(string s) {
if (hash.count(s)){
return hash[s];
}
for (int i = 1; i < s.size(); i++){
if (s[i - 1] == '+' && s[i] == '+'){
string next = s.substr(0, i - 1) + "--" + s.substr(i + 1);
if (!canWin(next)){
hash[next] = false;
return true;
}
hash[s] = true;
}
}
return false;
}
private:
unordered_map<string, bool> hash;
};