- Count Numbers with Unique Digits QuestionEditorial Solution My Submissions
Total Accepted: 13025
Total Submissions: 29945
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.Show More Hint
Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
这道题就是找规律。。。
题意:给定非负的整数n,求在 0 ≤ x < 10n 中,有多少每个位上的数字互不相同的数? 如 n =2 时,范围为[0,100], 共有91个数(除了11,22,33,44,55,66,77,88,99)
思路:
排列组合题。
设i为长度为i的各个位置上数字互不相同的数。
i==1 : 1 0(0~9共10个数,均不重复)
i==2: 9 * 9 (第一个位置上除0外有9种选择,第2个位置上除第一个已经选择的数,还包括数字0,也有9种选择)
i ==3: 9* 9 * 8 (前面两个位置同i==2,第三个位置除前两个位置已经选择的数还有8个数可以用)
……
i== n: 9 * 9 * 8 *…… (9-i+2)
需要注意的是,9- i + 2 >0 即 i < 11,也就是i最大为10,正好把每个数都用了一遍。
so , 其实可以算出来然后打表的,然后速度就飞快→_→
public class Solution {
public int countNumbersWithUniqueDigits(int n) {
n = Math.min(n, 10);
int[] dp = new int[n+1];
dp[0] = 1;
for(int i = 1; i <= n; i++)
{
dp[i] = 9;
for(int x = 9; x >= 9-i+2; x--)
{
dp[i] *= x;
}
}
int res = 0;
for(int i = 0; i < dp.length; i++)
{
res += dp[i];
}
return res;
}
}