- 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
- 41 lines of Python from the credited upstream file 2801.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 countSteppingNumbers(self, low: str, high: str) -> int:3 MOD = 1_000_000_0074 low = '0' * (len(high) - len(low)) + low5 6 @functools.lru_cache(None)7 def dp(8 i: int,9 prevDigit: int,10 isLeadingZero: bool,11 tight1: bool,12 tight2: bool,13 ) -> int:14 """15 Returns the number of valid integers, considering the i-th digit, where16 `prevDigit` is the previous digit, `tight1` indicates if the current17 digit is tightly bound for `low`, and `tight2` indicates if the current18 digit is tightly bound for `high`.19 """20 if i == len(high):21 return 122 23 res = 024 minDigit = int(low[i]) if tight1 else 025 maxDigit = int(high[i]) if tight2 else 926 27 for d in range(minDigit, maxDigit + 1):28 nextTight1 = tight1 and (d == minDigit)29 nextTight2 = tight2 and (d == maxDigit)30 if isLeadingZero:31 32 res += dp(i + 1, d, isLeadingZero and d ==33 0, nextTight1, nextTight2)34 elif abs(d - prevDigit) == 1:35 res += dp(i + 1, d, False, nextTight1, nextTight2)36 res %= MOD37 38 return res39 40 return dp(0, -1, True, True, True)41