The key idea is to count numbers with unique digits by considering how many ways we can fill each digit position without repeating digits. For each length k (from 1 to n), we calculate the number of unique-digit numbers of length k and sum them up.
classSolution {
public:int countNumbersWithUniqueDigits(int n) {
if (n ==0) return1;
int ans =1, mul =9;
for (int k =1; k <= n && k <=10; ++k) {
int cnt = mul;
for (int i =0; i < k -1; ++i)
cnt *= (9- i);
ans += cnt;
}
return ans;
}
};
classSolution {
publicintcountNumbersWithUniqueDigits(int n) {
if (n == 0) return 1;
int ans = 1;
for (int k = 1; k <= n && k <= 10; k++) {
int cnt = 9, mul = 9;
for (int i = 0; i < k - 1; i++) {
cnt *= mul;
mul--;
}
ans += cnt;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funcountNumbersWithUniqueDigits(n: Int): Int {
if (n ==0) return1var ans = 1for (k in1..minOf(n, 10)) {
var cnt = 9var mul = 9 repeat(k - 1) {
cnt *= mul
mul-- }
ans += cnt
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defcountNumbersWithUniqueDigits(self, n: int) -> int:
if n ==0:
return1 ans =1for k in range(1, min(n, 10) +1):
cnt =9 mul =9for _ in range(k -1):
cnt *= mul
mul -=1 ans += cnt
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfncount_numbers_with_unique_digits(n: i32) -> i32 {
if n ==0 { return1; }
letmut ans =1;
for k in1..=n.min(10) {
letmut cnt =9;
letmut mul =9;
for _ in0..(k-1) {
cnt *= mul;
mul -=1;
}
ans += cnt;
}
ans
}
}