Can I Win
Master this topic with zero to advance depth.
Can I Win
Two players take turns choosing integers from 1 to maxChoosableInteger without reuse. The first to reach desiredTotal wins. Return true if the first player can force a win.
Examples
Level I: Recursive Minimax (No Memoization)
Intuition
Explore all possible sequences of choosing numbers. A player wins if they can pick a number that reaches the total, or if there is a number they can pick such that the other player cannot win from the resulting state.
Thought Process
- Try choosing each available number .
- If , you win.
- Otherwise, if the other player cannot win from the state (remainder - , used numbers), you win.
- If no such exists, you lose.
Pattern: Game Theory Recursion
Level II: Recursion with Bitmask only
Intuition
Represent the state of used numbers with a 20-bit integer mask. This is more efficient for passing state through recursion but still suffers from exponential growth without memoization.
Level III: Optimal (Bitmask DP / Memoization)
Intuition
The state of the game is uniquely determined by which integers have been used. Since maxChoosableInteger is at most 20, we can use a bitmask of length 20 to represent the set of used numbers. Memoizing the results of these masks drastically reduces the number of computations.
Thought Process
- Use an integer
maskwhere the -th bit is 1 if number is used. - Store result of
canWin(mask)in a hash map or array. - Base cases:
desiredTotal <= 0or sum check.
Pattern: State Compression DP
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.