- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 41 lines of Java from the credited upstream file 2801.java.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 public int countSteppingNumbers(String low, String high) {3 final String lowWithLeadingZeros =4 String.valueOf('0').repeat(high.length() - low.length()) + low;5 Integer[][][][] mem = new Integer[high.length()][11][2][2];6 return count(lowWithLeadingZeros, high, 0, 10, true, true, true, mem);7 }8 9 private static final int MOD = 1_000_000_007;10 11 12 13 14 15 private int count(final String low, final String high, int i, int prevDigit,16 boolean isLeadingZero, boolean tight1, boolean tight2, Integer[][][][] mem) {17 if (i == high.length())18 return 1;19 if (mem[i][prevDigit][tight1 ? 1 : 0][tight2 ? 1 : 0] != null)20 return mem[i][prevDigit][tight1 ? 1 : 0][tight2 ? 1 : 0];21 22 int res = 0;23 final int minDigit = tight1 ? low.charAt(i) - '0' : 0;24 final int maxDigit = tight2 ? high.charAt(i) - '0' : 9;25 26 for (int d = minDigit; d <= maxDigit; ++d) {27 final boolean nextTight1 = tight1 && (d == minDigit);28 final boolean nextTight2 = tight2 && (d == maxDigit);29 if (isLeadingZero)30 31 res += count(low, high, i + 1, d, isLeadingZero && d == 0, nextTight1, nextTight2, mem);32 else if (Math.abs(d - prevDigit) == 1)33 34 res += count(low, high, i + 1, d, false, nextTight1, nextTight2, mem);35 res %= MOD;36 }37 38 return mem[i][prevDigit][tight1 ? 1 : 0][tight2 ? 1 : 0] = res;39 }40}41