題目:Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n.
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])
難度:medium 通過率:44.4%
一開始看到題目給的例子,除去了11、22、……99,所以一開始想用排除法做,求出有重複數字的數的數目,再用總數目去減,想找出一個規律來,但算着算着發現要考慮很多情況,所以想着直接計算,於是直接用排列組合思想計算即可。用數組count存儲當數字爲i位時不重複數字的個數,然後再直接加起來即可。
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
int sum = 1;
for(int i = 0; i < n; i++) {
int temp = 9;
for(int j = 9; j >= 10-i; j--) {
temp *= j;
}
sum+=temp;
}
return sum;
}
};