LC.P357[统计各位数字都不同的数字个数]

方法一:乘法原理

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int countNumbersWithUniqueDigits(int n) {
if (n == 0) return 1;
int ans = 10;
for (int i = 2, last = 9; i <= n; ++i) {
int cur = last * (10 - i + 1);
ans += cur;
last = cur;
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

方法二:数位DP

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
45
46
47
48
49
class Solution {
// f[l][r] 代表 i * (i + 1) * ... * (j - 1) * j
static int[][] f = new int[10][10];
static {
for (int i = 1; i < 10; i++) {
for (int j = i; j < 10; j++) {
int cur = 1;
for (int k = i; k <= j; k++) cur *= k;
f[i][j] = cur;
}
}
}

privatint dp(int x) {
int t = x;
List<Integer> nums = new ArrayList<>();
while (t != 0) {
nums.add(t % 10);
t /= 10;
}
int n = nums.size();
if (n <= 1) return x + 1; // [0, 9]
// 位数和 x 相同(res1 + res2)
int ans = 0;
for (int i = n - 1, p = 1, s = 0; i >= 0; i--, p++) {
int cur = nums.get(i), cnt = 0;
for (int j = cur - 1; j >= 0; j--) {
if (i == n - 1 && j == 0) continue;
if (((s >> j) & 1) == 0) cnt++;
}
int a = 10 - p, b = a - (n - p) + 1;
ans += b <= a ? cnt * f[b][a] : cnt;
if (((s >> cur) & 1) == 1) break;
s |= (1 << cur);
if (i == 0) ans++;
}
// 位数比 x 少(res3)
ans += 10;
for (int i = 2, last = 9; i < n; i++) {
int cur = last * (10 - i + 1);
ans += cur; last = cur;
}
return ans;
}

public int countNumbersWithUniqueDigits(int n) {
return dp((int)Math.pow(10, n) - 1);
}
}