Total Accepted: 1016
Total Submissions: 2355
Difficulty: Medium
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])
Hint:
- A direct way is to use the backtracking approach.
- Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n.
- This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics.
- Let f(k) = count of numbers with unique digits with length equals k.
- f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].
Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Count Numbers with Unique Digits思路:题目要求找到所有没有重复数字构成的数,分解问题考虑:
n位数包含了n-1位提供的所有答案,也就是说只要考虑n位数的情况。
在所有的n-1位数提供的答案中,n位数不重复的等于n-1位数的总和*(11-n),比如2位数,可以补充的选择是8个(则n-1=2;补充的数是10-2=8)
GitHub地址:https://github.com/corpsepiges/leetcode
public class Solution {
List<Integer> list;
List<Integer> sumList;
public int countNumbersWithUniqueDigits(int n) {
if(list==null){
list=new ArrayList<Integer>();
sumList=new ArrayList<Integer>();
list.add(1);
list.add(9);
sumList.add(1);
sumList.add(10);
}
for(int i=sumList.size();i<=n;i++){
list.add(list.get(i-1)*(9-i+2));
sumList.add(sumList.get(i-1)+list.get(i));
}
return sumList.get(n);
}
}
本文介绍了一种高效算法,用于解决LeetCode上的题目“Count Numbers with Unique Digits”,即计算在给定范围内有多少个不含重复数字的整数。通过递归回溯与动态规划两种方法的对比,详细阐述了解决方案的设计思路。
1890

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



