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])
一刷
题解:
f(k) = 9 * 9 * 8 * ... (9 - k + 2)
因为如果已经有两个数,那么接下来的选择就是10-2,..., 以此类推。然后sum up f(k)
public class Solution {
public int countNumbersWithUniqueDigits(int n) {
if(n == 0) return 1;
int res = 10, cnt = 9;
for(int i=2; i<=n; i++){
cnt *= (11-i);
res += cnt;
}
return res;
}
}
二刷
同上。
class Solution {
public int countNumbersWithUniqueDigits(int n) {
if(n == 0) return 1;
int cnt = 9, res = 10;
for(int i=2; i<=n; i++){
cnt*= (11 - i);
res += cnt;
}
return res;
}
}