Leetcode 294.翻转游戏 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.

做法:这题被LC 锁了,必须得充会员才可以看,我这里用C++实现下吧。  结合上篇文章:博客

这题得做法就是当前字符串 如果反转 这两个连续的 ++  那么剩余的状态为 必败状态的话,此状态就是必胜状态。

那么dfs 一下就可以了。很伤的是  这题没说字符串的长度,所以有点不敢dfs暴力写。看了题解是dfs 才敢这么写。

#include<bits/stdc++.h>
using namespace std;
const int N=1e2+10;
string s;
int run(string s)
{

    //cout<<s<<endl;
    for(int i=0;i<s.size();++i){
        if(i+1<s.size()&&s[i]=='+'&&s[i+1]=='+'
            &&!run(s.substr(0,i)+s.substr(i+2))) return 1;
    }
    return 0;
}
int main()
{
    cin>>s;
    if(run(s)) printf("First");
    else puts("Second");
    return 0;
}
/*
1100
*/

猜你喜欢

转载自blog.csdn.net/qq_41286356/article/details/106999797