Can I Win — LeetCode 464 Python Solution
MediumBit ManipulationMemoizationMathDynamic ProgrammingBitmaskGame Theory
- Problem
- #464
- Pattern
- Bit Manipulation
- Reading time
- 3 min
- Source
- leetcode.com
The problem
In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins.
Example
- Input
- maxChoosableInteger = 10, desiredTotal = 11
- Output
- false
- Explanation
- No matter which integer the first player choose, the first player will lose.
Python solution
Python
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
@cache
def dfs(mask: int, s: int) -> bool:
for i in range(1, maxChoosableInteger + 1):
if mask >> i & 1 ^ 1:
if s + i >= desiredTotal or not dfs(mask | 1 << i, s + i):
return True
return False
if (1 + maxChoosableInteger) * maxChoosableInteger // 2 < desiredTotal:
return False
return dfs(0, 0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(2^n) |
| Space | O(2^n) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 464. Can I Win is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 464. Can I Win?
- LeetCode 464. Can I Win is rated Medium on LeetCode.
- What is the time complexity of LeetCode 464. Can I Win?
- The Python solution on this page runs in O(2^n).
- What is the space complexity of LeetCode 464. Can I Win?
- The Python solution on this page uses O(2^n) auxiliary space.
- What topics does LeetCode 464. Can I Win cover?
- LeetCode 464. Can I Win is tagged Bit Manipulation, Memoization, Math, Dynamic Programming, Bitmask and Game Theory on LeetCode.