- 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.
解题思路1:
根据组合数学即可得出答案:
n = 0, dp[0] = 1;
n = 1, dp[1] = c(9,1) + dp[0];
n = 2, dp[2] = c(9,1)*a(9,1) + dp[1];
n = 3, dp[3] = c(9,1)*a(9,2)+ dp[2];
….
n = k, dp[k] = c(9,1)*a(9,k-1) + dp[k-1];
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
vector<int> dp(n,0);
int sum = 0;
if(n == 0){
return 1;
}
dp[0] = 1;
for(int i = 1;i <= n; ++i){
if(n < 10){
sum += dp[i-1];
dp[i] = sum + dp[i-1]*(10-i);// dp[i] = sum(dp[0]+...+dp[i-1]) + dp[i-1]*(10-i);
}else{
dp[i] = dp[i-1];
}
}
return dp[n];
}
};