- 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
- 34 lines of Python from the credited upstream file 3352.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 countKReducibleNumbers(self, s: str, k: int) -> int:3 MOD = 1_000_000_0074 ops = self._getOps(s)5 6 @functools.lru_cache(None)7 def dp(i: int, setBits: int, tight: bool) -> int:8 """9 Returns the number of positive integers less than n that are k-reducible,10 considering the i-th digit, where `setBits` is the number of set bits in11 the current number, and `tight` indicates if the current digit is12 tightly bound.13 """14 if i == len(s):15 return int(ops[setBits] < k and not tight)16 17 res = 018 maxDigit = int(s[i]) if tight else 119 20 for d in range(maxDigit + 1):21 nextTight = tight and (d == maxDigit)22 res += dp(i + 1, setBits + d, nextTight)23 res %= MOD24 return res25 26 return dp(0, 0, True) - 1 27 28 def _getOps(self, s: str) -> int:29 """Returns the number of operations to reduce a number to 0."""30 ops = [0] * (len(s) + 1)31 for num in range(2, len(s) + 1):32 ops[num] = 1 + ops[num.bit_count()]33 return ops34