LeetCode 357
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.
Solution:
题意是返回0~10的n次方间,每个位数上的数字都不相同的数的总数。
根据不同的总位数n进行分析,num为位数为n时符合条件的数的总数。
n = 0时,num = 1;
n = 1时,num = 9;
n = 2时,num = 9*9;
n = 3时,num = 9*9*8;
….
n = 10时,num = 9*9*8*7*6*5*4*3*2*1;
hint:第一位有9个选择(除了0),第二位还剩9个选择(包括了0),第三位还有8个选择……
最后的返回值为所有可能的n的取值对应的num之和
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if(n == 0)
return 1;
if(n > 10)
n = 10;
int result = 1;
for(int i = 1; i <= n; i++)
result += getNum(i);
return result;
}
int getNum(int n) {
if(n == 0) {
return 1;
} else if(n == 1) {
return 9;
} else {
int result = 9;
for(int i = 0; i < n-1; i++)
result = result*(9-i);
return result;
}
}
};