-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
44 lines (41 loc) · 1.11 KB
/
Solution.java
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 {
private int d;
private int[] a = new int[11];
private int[][] dp = new int[11][11];
public int digitsCount(int d, int low, int high) {
this.d = d;
return f(high) - f(low - 1);
}
private int f(int n) {
for (var e : dp) {
Arrays.fill(e, -1);
}
int len = 0;
while (n > 0) {
a[++len] = n % 10;
n /= 10;
}
return dfs(len, 0, true, true);
}
private int dfs(int pos, int cnt, boolean lead, boolean limit) {
if (pos <= 0) {
return cnt;
}
if (!lead && !limit && dp[pos][cnt] != -1) {
return dp[pos][cnt];
}
int up = limit ? a[pos] : 9;
int ans = 0;
for (int i = 0; i <= up; ++i) {
if (i == 0 && lead) {
ans += dfs(pos - 1, cnt, lead, limit && i == up);
} else {
ans += dfs(pos - 1, cnt + (i == d ? 1 : 0), false, limit && i == up);
}
}
if (!lead && !limit) {
dp[pos][cnt] = ans;
}
return ans;
}
}