Flip Game II — LeetCode 294 Python Solution
MediumLeetCode PremiumMemoizationMathDynamic ProgrammingBacktrackingGame Theory
- Problem
- #294
- Pattern
- Backtracking
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are playing a Flip Game with your friend. You are given a string currentState that contains only '+' and '-'.
Example
- Input
- currentState = "++++"
- Output
- true
- Explanation
- The starting player can guarantee a win by flipping the middle "++" to become "+--+".
Python solution
Python
class Solution:
def canWin(self, currentState: str) -> bool:
@cache
def dfs(mask):
for i in range(n - 1):
if (mask & (1 << i)) == 0 or (mask & (1 << (i + 1)) == 0):
continue
if dfs(mask ^ (1 << i) ^ (1 << (i + 1))):
continue
return True
return False
mask, n = 0, len(currentState)
for i, c in enumerate(currentState):
if c == '+':
mask |= 1 << i
return dfs(mask)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 294. Flip Game II is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 294. Flip Game II?
- LeetCode 294. Flip Game II is rated Medium on LeetCode.
- What topics does LeetCode 294. Flip Game II cover?
- LeetCode 294. Flip Game II is tagged Memoization, Math, Dynamic Programming, Backtracking and Game Theory on LeetCode.
- Is LeetCode 294. Flip Game II a premium problem?
- Yes. LeetCode 294. Flip Game II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.