您的位置:首页 > 其它

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

2016-03-20 06:34 435 查看
题目链接: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.

思路:枚举每一种情况,然后递归到下一层,看对手可不可以赢,如果对手有赢得情况那么就无法保证一定能赢。时间复杂度是指数。

还有O(n)时间内能解决的,不过有点麻烦,这个解面试一般够用了。有兴趣的再去找找吧。

代码如下:

class Solution {
public:
bool canWin(string s) {
int len = s.size();
vector<string> strs;
for(int i = 0; i< len-1; i++)
if(s[i] == '+' && s[i+1] == '+')
strs.push_back(s.substr(0, i)+"--"+s.substr(i+2));
for(auto str: strs)
if(!canWin(str))
return true;
return false;
}
};
参考:https://leetcode.com/discuss/73327/o-n-time-o-1-space-c-solution
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: