这道题乏善可陈。最基本的dfs 和高中概率题
解法一:dfs
int countNumbersWithUniqueDigits(int n) {
unordered_set<int> used;
int res=1;
helper(res, used, n);
return res;
}
void helper(int& res, unordered_set<int>& used, int n){
if(n==0)
return;
for(int i=0;i<=9;++i){
if(used.size()==0&&i==0)
continue;
if(used.find(i)==used.end()){
used.insert(i);
res++;
helper(res, used, n-1);
used.erase(i);
}
}
return;
}
解法二:概率
int countNumbersWithUniqueDigits(int n) {
if(n==0)
return 1;
vector<int> memo(n+1,1);
memo[1]=9;
int res=10;
for(int i=2;i<=9&&i<=n;++i){
memo[i]=memo[i-1]*(10-i+1);
res=res+memo[i];
//cout<<res<<" "<<memo[i]<<memo[i-1]<<" "<<(10-i+1)<<endl;
}
return res;
}