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])
这道题是要求从0到10n中各个数位都不同的数的个数,leetcode将他放到了动态规划类别中。
这道题我最先的想法是利用递归。以上述例子2来说,分2种情况。n = 1(2 - 1)的情况以及夹在n = 2和n = 1之间的情况,也就是2(n)位数的情况。对于一个n位数,使其各个数位上的数字都不相同,方法是比较简单的。所以这道题的答案也就出来了。
int countNumbersWithUniqueDigits(int n) {
if(n == 1){
return 10;
}
else if(n == 0){
return 1;
}
else{
int part = 9, count = 9; //part为计数,计算n位数中满足条件的数字个数,count为帮助计算的变量
for(int i = 0; i < n - 1; i++){
part *= count;
count--;
}
return countNumbersWithUniqueDigits(n - 1) + part;
}
}
if(n == 1){
return 10;
}
else if(n == 0){
return 1;
}
else{
int part = 9, count = 9; //part为计数,计算n位数中满足条件的数字个数,count为帮助计算的变量
for(int i = 0; i < n - 1; i++){
part *= count;
count--;
}
return countNumbersWithUniqueDigits(n - 1) + part;
}
}
我的方法也不知道算不算是动态规划,但是也算借用了动态规划的思想,只不过我是从最后一步一步往前推。
如有不足,请读者留言指教。
本文探讨了LeetCode上一道关于计算特定范围内具有唯一数字组合的数量的问题,并提供了一种递归解决方案,通过逐步向前推导的方式得出答案。
322

被折叠的 条评论
为什么被折叠?



