- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 45 lines of Python from the credited upstream file 3320.py.
- The implementation visibly relies on cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def countWinningSequences(self, s: str) -> int:3 MOD = 1_000_000_0074 5 @functools.lru_cache(None)6 def dp(i: int, prev: int, bob: int) -> int:7 """8 Returns the number of distinct sequences Bob can use to beat Alice for9 s[i..n), where the previous character is `prev` (0: F, 1: W, 2: E) and the10 number of points that Bob is having is `bob`.11 """12 if i == len(s):13 return int(bob > 0)14 15 f = 0 16 w = 0 17 e = 0 18 19 match s[i]:20 case 'F':21 if prev != 0:22 f = dp(i + 1, 0, bob) % MOD23 if prev != 1:24 w = dp(i + 1, 1, bob + 1) % MOD25 if prev != 2:26 e = dp(i + 1, 2, bob - 1) % MOD27 case 'W':28 if prev != 0:29 f = dp(i + 1, 0, bob - 1) % MOD30 if prev != 1:31 w = dp(i + 1, 1, bob) % MOD32 if prev != 2:33 e = dp(i + 1, 2, bob + 1) % MOD34 case 'E':35 if prev != 0:36 f = dp(i + 1, 0, bob + 1) % MOD37 if prev != 1:38 w = dp(i + 1, 1, bob - 1) % MOD39 if prev != 2:40 e = dp(i + 1, 2, bob) % MOD41 42 return f + w + e43 44 return (dp(0, 0, 0) + dp(0, 1, 0) + dp(0, 2, 0)) 2 % MOD45