https://leetcode.com/problems/count-numbers-with-unique-digits/
dfs解法:
class Solution {
int res;
void dfs(vector<bool>& used, int left) {
if(left == 0) {return;}
for(int i = 0; i <= 9; i++) {
if(used[i])
continue;
used[i] = true;
if(!i == 0)
res ++;
dfs(used,left-1);
used[i] = false;
}
}
public:
int countNumbersWithUniqueDigits(int n) {
if(n > 10)
n = 10;
vector<bool> used(10,false);
res = 0;
dfs(used,n);
return res+1;
}
};
dp解法?其实我这个应该算是找规律...:
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if(n > 10)
n = 10;
if(n <= 0) return 1;
if(n == 1) return 10;
int res = 10;
int count = 9;
int factor = 9;
for(int i = 2; i <= n; i++) {
count = count * factor;
factor--;
res += count;
}
return res;
}
};