357 Count Numbers with Unique Digits

1. Question

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example: Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding[11,22,33,44,55,66,77,88,99])

2. Implementation

(1) Backtracking
1
class Solution {
2
public int countNumbersWithUniqueDigits(int n) {
3
boolean[] used = new boolean[10];
4
int[] count = new int[1];
5
getNumbersWithUniqueDigits(0, n, used, count);
6
// 加1因为要算上刚开始的0
7
return 1 + count[0];
8
}
9
10
public void getNumbersWithUniqueDigits(int curLevel, int depth, boolean[] used, int[] count) {
11
if (curLevel == depth) {
12
return;
13
}
14
15
int start = curLevel == 0 ? 1 : 0;
16
17
for (int i = start; i < 10; i++) {
18
if (!used[i]) {
19
used[i] = true;
20
++count[0];
21
getNumbersWithUniqueDigits(curLevel + 1, depth, used, count);
22
used[i] = false;
23
}
24
}
25
}
26
}
Copied!
(2) DP
1
class Solution {
2
public int countNumbersWithUniqueDigits(int n) {
3
if (n > 10) {
4
return 0;
5
}
6
7
int[] dp = new int[11];
8
// 0个digit的时候,unique number是1, 这里我们把0当做
9
dp[0] = 1;
10
dp[1] = 9;
11
12
for (int i = 2; i <= n; i++) {
13
dp[i] = dp[i - 1] * (9 - i + 2);
14
}
15
16
int res = 0;
17
for (int i = 0; i <= n; i++) {
18
res += dp[i];
19
}
20
return res;
21
}
22
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(n!), 如果n > 10的话,时间复杂度为O(10!), 空间复杂度O(n)
DP: 时间复杂度O(n), 空间复杂度O(1)