|
| 1 | +/** |
| 2 | + * @param {string} low |
| 3 | + * @param {string} high |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | +var countSteppingNumbers = function (low, high) { |
| 7 | + const mod = 1000000007 |
| 8 | + let init = () => new Array(101) |
| 9 | + .fill(null) |
| 10 | + .map(() => |
| 11 | + new Array(2) |
| 12 | + .fill(null) |
| 13 | + .map(() => new Array(2).fill(null).map(() => new Array(11).fill(-1))), |
| 14 | + ) |
| 15 | +// console.log(dp) |
| 16 | + const helper = (pos, tight, isZero, prevDigit, s) => { |
| 17 | + if (pos === s.length) { |
| 18 | + if (isZero) return 0 |
| 19 | + return 1 |
| 20 | + } |
| 21 | + |
| 22 | + if (dp[pos][tight][isZero][prevDigit + 1] !== -1) |
| 23 | + return dp[pos][tight][isZero][prevDigit + 1] |
| 24 | + |
| 25 | + let res = 0 |
| 26 | + let limit |
| 27 | + |
| 28 | + if (tight) limit = parseInt(s[pos]) |
| 29 | + else limit = 9 |
| 30 | + |
| 31 | + for (let curDigit = 0; curDigit <= limit; curDigit++) { |
| 32 | + let newTight = tight |
| 33 | + if (tight && curDigit < limit) newTight = 0 |
| 34 | + |
| 35 | + let willBeZero = isZero |
| 36 | + if (isZero && curDigit > 0) willBeZero = 0 |
| 37 | + |
| 38 | + if (isZero) { |
| 39 | + res += helper(pos + 1, newTight, willBeZero, curDigit, s) |
| 40 | + res %= mod |
| 41 | + } else { |
| 42 | + if (Math.abs(curDigit - prevDigit) === 1) { |
| 43 | + res += helper(pos + 1, newTight, willBeZero, curDigit, s) |
| 44 | + res %= mod |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + dp[pos][tight][isZero][prevDigit + 1] = res |
| 50 | + return res |
| 51 | + } |
| 52 | + let dp = init() |
| 53 | + let l = helper(0, 1, 1, -1, low) |
| 54 | + |
| 55 | + dp = init() |
| 56 | + let r = helper(0, 1, 1, -1, high) |
| 57 | + |
| 58 | + let res = r - l |
| 59 | + res = (res + mod) % mod |
| 60 | + |
| 61 | + let add = true |
| 62 | + for (let i = 1; i < low.length; i++) { |
| 63 | + if (Math.abs(low[i] - low[i - 1]) !== 1) { |
| 64 | + add = false |
| 65 | + break |
| 66 | + } |
| 67 | + } |
| 68 | + if (add) res++ |
| 69 | + |
| 70 | + res %= mod |
| 71 | + return res |
| 72 | +} |
| 73 | + |
| 74 | +// another |
| 75 | + |
| 76 | + |
1 | 77 | const minus_mod = (x, y, mod) => ((x - y) % mod + mod) % mod; |
2 | 78 | const mod = 1e9 + 7, ll = BigInt; |
3 | 79 | let memo; |
|
0 commit comments