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])
Seems like there is a rule for it.
if n == 1, there will be 10 numbers [0 -- 9]
if n == 2, since we can't start from 0, if we start from 1, there will be 1*9, start with 2, there will be 1 * 9..... thus, n == 2, in total = 1*9*9
if n ==3, since we can't start from 0, if we start from 1*, there will be 1*9*8, start with 2, there will be 1*9*8 ... thus n == 3, in total = 1*9*9*8
if n == 4, since we can't start from 0, if start with 1**, there will be 1*9*8*7, start with 2, 1*9*8*7.... n ==3, in total = 1*9*9*8*7
.... the total is n==1 + n==2 + ... n == n
int fn(n) {
int n = 2;
int prev = 10;
int sum = 9;
while(n > 1) {
sum = sum * (9 - n + 2);
total = prev + sum;
n = n - 1;
}
return total;
}
Or use dp.
int countNumbersWithUniqueDigits(int n) {
if(!n) return 1;
vector<int> dp(n, 0);
dp[0] = 9;
for(int i = 1; i < n; ++i) {
dp[i] = dp[i-1] * (10 - i);
}
int sum = 0;
for(int i = 0; i < n; ++i) sum += dp[i];
return sum + 1;
}
257



被折叠的 条评论
为什么被折叠?



