[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:
you and your friend take turns to flip two consecutive
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
a win by flipping the middle
Follow up:
Derive your algorithm's runtime complexity.
思路:枚举每一种情况,然后递归到下一层,看对手可不可以赢,如果对手有赢得情况那么就无法保证一定能赢。时间复杂度是指数。
还有O(n)时间内能解决的,不过有点麻烦,这个解面试一般够用了。有兴趣的再去找找吧。
代码如下:
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
相关文章推荐
- Ubuntu制作本地源
- 安卓 画折线
- vc6 OpenThread
- [WebStrom] Cannot detect file change to trigger webpack re-compile
- 简易计算器(核心算法就是Shutting-Yard, 逆波兰式)
- @date2016-03-19(软件工程男的日常)
- 完美解决android studio启动Genymotion失败的‘unable to load VirtualBox….‘报错
- 技术大牛VS小菜鸟VS客户—南昌某局的项目纪实
- @date2016-03-18(软件工程男的日常)
- 配置PyCharm(背景色+字体大小+解释器选择)
- 3. Longest Substring Without Repeating Characters
- [TypeScript] Avoid any type
- use cmake to compile static library and test
- python中dir(), hasattr(), getattr(), setattr()的使用
- tab不显示为空格
- android坐标
- 将字符串变为数组,并遍历数组
- 关键字后面不加空格
- Android自定义TextView实现drawableLeft内容居中
- python中的装饰器Decorator用法