这个题一开始没有头绪,后来看了一下别人的思路,这个题可以这样想:
设一个数组dp,dp[i]表示的n=i的时候的答案,举个例子,如果n=3,那么他等于n=2的时候不重复数字的个数加上三位数中不重复数字的个数。这样可以用动态规划:
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
vector<int> res(n + 2, 0);
res[0] = 1;
res[1] = 10;
for(int i = 2; i <= n; ++i)
{
int x = 9;
for(int j = 0; j < i - 1; ++j)
{
x = x * (9 - j);
}
res[i] = res[i-1] + x;
}
return res[n];
}
};