LeetCode-Count Numbers with Unique Digits
2644 ワード
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Input: 2 Output: 91 Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99
Constraints:
0 <= n <= 8
解析F(0)=1 F(1)=10 F(2)=10+9(1番目の数は0にできない)9(1番目の数と同じではない数を0~9から選択できる)F(3)=10+99+998 F(4)=…
F(n) = F(n-1) + 9 * 8 * …* 9-n+1;
Example:
Input: 2 Output: 91 Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99
Constraints:
0 <= n <= 8
解析F(0)=1 F(1)=10 F(2)=10+9(1番目の数は0にできない)9(1番目の数と同じではない数を0~9から選択できる)F(3)=10+99+998 F(4)=…
F(n) = F(n-1) + 9 * 8 * …* 9-n+1;
public int countNumbersWithUniqueDigits(int n) {
if(n == 0) return 1;
int sum = 10;
int step = 9;
int K = 9;
for( int i = 0 ; i < n-1;i ++){
step = step *(K -i);
sum += step;
}
return sum;
}