357. Count Numbers with Unique Digit
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]
)
几点注意:
1.数字为0—9,10个
2.n>10 是 取n=10
3.rel[0] = 1;
rel[1] = 10;
rel[2] = rel[1] + (1~9)9 * (0~9去掉前面的)9
rel[3] = rel[2] + (1~9, 设取a)9*(0~9除了a,设取b)9*(0~9除ab)8
以此类推~~~~
class Solution {
public:int countNumbersWithUniqueDigits(int n) {
if (n == 0)
return 1;
if(n == 1)
return 10;
if (n == 2)
return 91;
if (n > 10)
n = 10;
int* rel = new int [n];
int del = 9;
rel[0] = 1;
rel[1] = 10;
rel[2] = 10 + 9*9;
for (int i = 3 ; i <= n ; i ++)
{
rel[i] = 9;
for (int j = 1 ; j < i ; j ++)
rel[i] *= 10-j;
rel[i] += rel[i-1];
}
return rel[n];
}
};