题目:
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]
)
思路:
当n=1时因为只有一个数字,所以0-9都是答案.当n>=2时,最高位可以为1-9任意一个数字,之后各位可以选择的数字个数依次为9, 8, 7, 6...,上一位选一个下一位就少了一种选择.
程序:
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if(n == 0)
return 1;
if(n <= 10)
{
vector<int> res(n,1);
for(int i = 1;i <= n;i++)
{
int sum = 9;
for(int j = 2;j <= i;j++)
sum *= (11 - j);
res[i] = res[i - 1] + sum;
}
return res[n];
}
else
{
vector<int> res(10,1);
for(int i = 1;i <= 10;i++)
{
int sum = 9;
for(int j = 2;j <= i;j++)
sum *= (11 - j);
res[i] = res[i - 1] + sum;
}
return res[10];
}
}
};