Solve for remaining 'digit' digits, with previous 'prev1' digit, and previous-previous 'prev2' digit, total sum of 'sum_max'. Pass around 'cache' to store/reuse intermediate results. >>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=True, cache={}) 9 >>> solve(digit=1,
(
digit: int, prev1: int, prev2: int, sum_max: int, first: bool, cache: dict[str, int]
)
| 11 | |
| 12 | |
| 13 | def solve( |
| 14 | digit: int, prev1: int, prev2: int, sum_max: int, first: bool, cache: dict[str, int] |
| 15 | ) -> int: |
| 16 | """ |
| 17 | Solve for remaining 'digit' digits, with previous 'prev1' digit, and |
| 18 | previous-previous 'prev2' digit, total sum of 'sum_max'. |
| 19 | Pass around 'cache' to store/reuse intermediate results. |
| 20 | |
| 21 | >>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=True, cache={}) |
| 22 | 9 |
| 23 | >>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=False, cache={}) |
| 24 | 10 |
| 25 | """ |
| 26 | if digit == 0: |
| 27 | return 1 |
| 28 | |
| 29 | cache_str = f"{digit},{prev1},{prev2}" |
| 30 | if cache_str in cache: |
| 31 | return cache[cache_str] |
| 32 | |
| 33 | comb = 0 |
| 34 | for curr in range(sum_max - prev1 - prev2 + 1): |
| 35 | if first and curr == 0: |
| 36 | continue |
| 37 | |
| 38 | comb += solve( |
| 39 | digit=digit - 1, |
| 40 | prev1=curr, |
| 41 | prev2=prev1, |
| 42 | sum_max=sum_max, |
| 43 | first=False, |
| 44 | cache=cache, |
| 45 | ) |
| 46 | |
| 47 | cache[cache_str] = comb |
| 48 | return comb |
| 49 | |
| 50 | |
| 51 | def solution(n_digits: int = 20) -> int: |