leetcode 293.Flip Game(lintcode 914) 、294.Flip Game II(lintcode 913)

914. Flip Game

https://www.cnblogs.com/grandyang/p/5224896.html

从前到后遍历,遇到连续两个'+',就将两个加号变成'-'组成新的字符串加入到结果中。

class Solution {
public:
    vector<string> generatePossibleNextMoves(string &s) {
        // write your code here
        vector<string> result;  
        for(int i = 1;i < s.size();i++){
            if(s[i] == '+' && s[i-1] == '+')
                result.push_back(s.substr(0,i-1) + "--" + s.substr(i+1,s.size() - i - 1));
        }
        return result;
    }
};

 913. Flip Game II

这个题是看先手变换的是否会赢。

方法与Flip Game类似,遍历字符串,然后递归找下一个是否是能修改,将修改后的字符串传入到递归的结果中。

https://www.cnblogs.com/grandyang/p/5226206.html

下面这个应该是leetcode上的格式,没有使用引用,这个代码直接贴到lintcode上会报错。

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;
    }
};

修改后lintcode上的代码。

class Solution {
public:
    /**
     * @param s: the given string
     * @return: if the starting player can guarantee a win
     */
    bool canWin(string &s) {
        // write your code here
        for(int i = 1;i < s.size();i++){
            if(s[i] == '+' && s[i-1] == '+'){
                string tmp = s.substr(0,i-1) + "--" + s.substr(i+1);
                if(!canWin(tmp))
                    return true;
            }
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/ymjyqsx/p/10841419.html