1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { String[] digits; char[] s; int[] dp;
public int atMostNGivenDigitSet(String[] digits, int n) { this.digits = digits; s = Integer.toString(n).toCharArray(); dp = new int[s.length]; Arrays.fill(dp, -1); return f(0, true, false); }
private int f(int i, boolean isLimit, boolean isNum) { if (i == s.length) return isNum ? 1 : 0; if (!isLimit && isNum && dp[i] >= 0) return dp[i]; int ans = 0; if (!isNum) { ans = f(i + 1, false, false); } char up = isLimit ? s[i] : '9'; for (String digit : digits) { if (digit.charAt(0) > up) break; ans += f(i + 1, isLimit && digit.charAt(0) == up, true); } if (!isLimit && isNum) dp[i] = ans; return ans; } }
|