LeetCode 题解(277) :Flip Game II
来源:互联网 发布:添加字段sql 编辑:程序博客网 时间:2024/05/24 03:54
题目:
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.
递归或者 Game Theory。
C++版:
class Solution {public: bool canWin(string s) { int cur = 0, maxL = 0; vector<int> subGames; for(int i = 0; i < s.length(); i++) { if(s[i] == '+') { cur++; if(cur >= 2 && (i == s.length() - 1 || s[i + 1] == '-')) { subGames.push_back(cur); maxL = max(maxL, cur); cur = 0; } } else cur = 0; } vector<int> eachGame(maxL + 1, 0); for(int i = 2; i <= maxL; i++) { unordered_set<int> nums; for(int j = 0; j < i / 2; j++) { int k = i - j - 2; nums.insert(eachGame[j] ^ eachGame[k]); } eachGame[i] = firstMissingNumber(nums); } int result = 0; for(auto i : subGames) result ^= eachGame[i]; return result != 0; } int firstMissingNumber(unordered_set<int>& s) { int l = s.size(); for(int i = 0; i < l; i++) if(s.count(i) == 0) return i; return l; }};
Python版:
class Solution(object): def canWin(self, s): """ :type s: str :rtype: bool """ if len(s) < 2: return False for i in range(len(s) - 1): if s[i] == '+' and s[i+1] == '+' and not self.canWin(s[:i] + '-' + s[i+2:]): return True return False
0 0
- LeetCode 题解(277) :Flip Game II
- *LeetCode-Flip Game II
- LeetCode 题解(276) :Flip Game
- LeetCode 294. Flip Game II
- Leetcode 293. Flip Game & 294. Flip Game II
- [leetcode] 294. Flip Game II 解题报告
- [Leetcode] 294. Flip Game II 解题报告
- leetcode Jump Game II 题解
- poj1753 flip game题解
- LeetCode 294. Flip Game II(反转游戏II)
- [LeetCode294] Flip Game II
- [LeetCode294]Flip Game II
- [leetcode294]Flip Game II
- [LeetCode294] Flip Game II
- Flip Game II
- Flip Game II
- 294. Flip Game II
- Leetcode 294. Flip Game II (回溯,记忆化)
- 算法实习生之路——基于Json串的UCB算法加载性能测试
- Amazon OA2准备——最大公约数
- Spring - MVC Framework 教程
- LeetCode 题解(275) : Nim Game
- LeetCode 题解(276) :Flip Game
- LeetCode 题解(277) :Flip Game II
- IOS消息推送之APNS
- 小团队 机器学习
- 用R&Python在云端运行可扩展数据科学
- 易开发创始人潘俊勇:这些年我遇到的那些坑
- ThoughtWorks面试失败
- 20151018
- 黑马程序员——Java多态
- ReactiveCocoa基础篇