[leetcode] 294. Flip Game II 解题报告

题目链接:https://leetcode.com/problems/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.

For example, given s = "++++", return true. The starting player can guarantee a win by flipping the middle "++" to become "+--+".

Follow up:
Derive your algorithm's runtime complexity.


思路:枚举每一种情况,然后递归到下一层,看对手可不可以赢,如果对手有赢得情况那么就无法保证一定能赢。时间复杂度是指数。但是通过简单的记忆化就可以优化很多的时间, 但是具体能优化多少还要看具体情况. 在本题的测试用例中不带记忆化1500ms+, 加了之后可以达到50ms+, 还是很有用的.

代码如下:

class Solution {
public:
    bool canWin(string s) {
        if(hash.count(s)) return hash[s];
        for(int i = 0; i < (int)s.size() -1; i++)
        {
            if(s.substr(i,2)!="++") continue;
            string str = s.substr(0,i)+"--"+s.substr(i+2);
            if(!canWin(str)) { hash[str] = false ; return true; }
            hash[str] = true;
        }
        return false;
    }
private:
    unordered_map hash;
};



你可能感兴趣的:(leetcode,leetcode,博弈论)