293. Flip Game && 294. Flip Game II

293. Flip Game

问题描述:

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 compute all possible states of the string after one valid move.

Example:

Input: s = "++++"
Output: 
[
  "--++",
  "+--+",
  "++--"
]

Note: If there is no valid move, return an empty list [].

解题思路:

遍历字符串。

需要注意的一点是,s.size()返回的是size_t的类型,其实质为一个无符号整数。

当它等于0时,在这里s.size() - 1 得到的值是 18446744073709551615

此时可以跳进循环,会发生错误!

代码:

class Solution {
public:
    vector<string> generatePossibleNextMoves(string s) {
        vector<string> ret;
        int n = s.size();
        for(int i = 0; i < n - 1;i++){
            if(s[i] == '+' && s[i+1] == '+'){
                string temp = s;
                temp[i] = '-';
                temp[i+1] = '-';
                ret.push_back(temp);
            }
        }
        return ret;
    }
};

----------------下一题分割线------------------------

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

Follow up:
Derive your algorithm's runtime complexity.

解题思路:

这道题一开始我解题方向找错了,由于是从292. Nim Game过来了,我以为要用DP或者什么其他的很巧妙的方法。

然后也有理解错题意的过程。

这道题给出的字符串中既包含‘+’ 也包含‘-’

所以我们可以用枚举来进行检查。

并且只要有一个能取得胜利,那我们就可以取得胜利。

代码:

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) {
        unordered_map<string, bool> m;
        return dfs(s, m);
    }
    bool dfs(string& s, unordered_map<string, bool>& m){
        if(m.count(s)) return m[s];
       for(int i=1; i<s.size(); i++){
            if(s[i-1]=='+' && s[i]=='+'){
                s[i-1] = '-'; s[i] = '-';
                if(!dfs(s, m)) {
                    s[i-1] = '+'; s[i] = '+'; 
                    m[s] = true;
                    return true;
                };
                s[i-1] = '+'; s[i] = '+';
            }
        }
        m[s] = false;
        return false;
    }
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9216170.html