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]
)
Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.
找规律题目。
n = 0时,count = 1;
n = 1时,count = 1 + 9 = 10;
n = 2时,count = 10 + 9*9 = 91;
n = 3时,count = 91 + 9*9*8;
n = 4时,count = count(n=3) + 9*9*8*7;
....
n = 10时,count = count(n=9) + 9*9*8*7*6*5*4*3*2*1;
程序如下所示:
class Solution {
public int countNumbersWithUniqueDigits(int n) {
int cnt = 1;
for (int i = 0; i < n; ++ i){
int val = 9;
for (int j = 0; i > 0&&j < i; ++ j){
val *= 9 - j;
}
cnt += val;
}
return cnt;
}
}