- 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
- 35 lines of Python from the credited upstream file 3490.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 beautifulNumbers(self, l: int, r: int) -> int:3 @functools.lru_cache(None)4 def dp(5 s: str,6 i: int,7 tight: bool,8 isLeadingZero: bool,9 hasZero: bool,10 sum: int,11 prod: int,12 ) -> int:13 if i == len(s):14 if isLeadingZero:15 return 016 return 1 if hasZero or prod % sum == 0 else 017 if not isLeadingZero and hasZero and not tight:18 return 10 ** (len(s) - i)19 20 res = 021 maxDigit = int(s[i]) if tight else 922 23 for d in range(maxDigit + 1):24 nextTight = tight and (d == maxDigit)25 nextIsLeadingZero = isLeadingZero and d == 026 nextHasZero = not nextIsLeadingZero and d == 027 nextProd = 1 if nextIsLeadingZero else prod * d28 res += dp(s, i + 1, nextTight, nextIsLeadingZero,29 nextHasZero, sum + d, nextProd)30 31 return res32 33 return (dp(str(r), 0, tight=True, isLeadingZero=True, hasZero=False, sum=0, prod=1) -34 dp(str(l - 1), 0, tight=True, isLeadingZero=True, hasZero=False, sum=0, prod=1))35