- 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
- 40 lines of Java from the credited upstream file 1012.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 numDupDigitsAtMostN(int n) {3 return n - countSpecialNumbers(n);4 }5 6 7 private int countSpecialNumbers(int n) {8 final int digitSize = (int) Math.log10(n) + 1;9 Integer[][][] mem = new Integer[digitSize + 1][1 << 10][2];10 return count(String.valueOf(n), 0, 0, true, mem) - 1; 11 }12 13 14 15 16 private int count(final String s, int i, int used, boolean tight, Integer[][][] mem) {17 if (i == s.length())18 return 1;19 if (mem[i][used][tight ? 1 : 0] != null)20 return mem[i][used][tight ? 1 : 0];21 22 int res = 0;23 final int maxDigit = tight ? s.charAt(i) - '0' : 9;24 25 for (int d = 0; d <= maxDigit; ++d) {26 27 if ((used >> d & 1) == 1)28 continue;29 30 final boolean nextTight = tight && (d == maxDigit);31 if (used == 0 && d == 0) 32 res += count(s, i + 1, used, nextTight, mem);33 else34 res += count(s, i + 1, used | 1 << d, nextTight, mem);35 }36 37 return mem[i][used][tight ? 1 : 0] = res;38 }39}40