本题的意思是给定一个非负整数n,要求出满足0 <= x < 10 ^ n范围的所有所含数字不重复的数的数量。
我采用动态规划的思想解决此题。我们令f(n)表示长度为n的数中所含数字不重复的数的数量。那么,很明显,f(1) = 10。对于f(2)来说,第一位有9种选择,在第一位选定后,第二位有9种选择,所以f(2) = 81。相似地,f(3) = f(2) * 8。依此类推,f(4) = f(3) * 7,……,f(10) = f(9) * 1。当n > 10的时候,f(n) = 0。综上所述,此题的解就是f(1) + f(2) + …… + f(n)。
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if (n == 0) {
return 1;
}
int init_ = 10;
int uniqueDigits = 9;
int count = 9;
while (n-- > 1 && count > 0) {
uniqueDigits = uniqueDigits * count;
init_ += uniqueDigits;
count--;
}
return init_;
}
};