- 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 3352.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks 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 countKReducibleNumbers(String s, int k) {3 Integer[][][] mem = new Integer[s.length()][s.length() + 1][2];4 return count(s, 0, 0, true, k, getOps(s), mem) - 1; 5 }6 7 private static final int MOD = 1_000_000_007;8 9 10 11 12 13 private int count(String s, int i, int setBits, boolean tight, int k, int[] ops,14 Integer[][][] mem) {15 if (i == s.length())16 return (ops[setBits] < k && !tight) ? 1 : 0;17 if (mem[i][setBits][tight ? 1 : 0] != null)18 return mem[i][setBits][tight ? 1 : 0];19 20 int res = 0;21 final int maxDigit = tight ? s.charAt(i) - '0' : 1;22 23 for (int d = 0; d <= maxDigit; ++d) {24 final boolean nextTight = tight && (d == maxDigit);25 res += count(s, i + 1, setBits + d, nextTight, k, ops, mem);26 res %= MOD;27 }28 29 return mem[i][setBits][tight ? 1 : 0] = res;30 }31 32 33 private int[] getOps(String s) {34 int[] ops = new int[s.length() + 1];35 for (int num = 2; num <= s.length(); ++num)36 ops[num] = 1 + ops[Integer.bitCount(num)];37 return ops;38 }39}40