2019独角兽企业重金招聘Python工程师标准>>>
问题:
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n.
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]
)
解决:
【题意】计算有n位数的数字在0~10^n范围内,各个位数字不同的个数。
① 直接计算。
n = 1 ----> 10 <--- 没有重复
n = 2 ----> 91 <--- 排除11,22,33,44,55,66,77,88,99
n = 3 ----> 739 <--- 排除类似111、121、112、211的数字
当n = 1时因为只有一个数字,所以0 - 9都是答案.当n >= 2时,最高位可以为1 - 9任意一个数字,之后从i = 2开始可以选择的数字个数依次为9, 8, 7, 6...,(9 - i + 2)上一位选一个下一位就少了一种选择。
class Solution {//0ms
public int countNumbersWithUniqueDigits(int n) {
if (n == 0) return 1;
if (n == 1) return 10;
int res = 10;
int tmp = 9;
for (int i = 2;i <= n;i ++){
tmp *= (9 - i + 2);
res += tmp;
}
return res;
}
}
② 动态规划。
Following the hint. Let f(n) = count of number with unique digits of length n.
f(1) = 10. (0, 1, 2, 3, ...., 9)
f(2) = 9 * 9. Because for each number i from 1, ..., 9, we can pick j to form a 2-digit number ij and there are 9 numbers that are different from i for j to choose from.
f(3) = f(2) * 8 = 9 * 9 * 8. Because for each number with unique digits of length 2, say ij, we can pick k to form a 3 digit number ijk and there are 8 numbers that are different from i and j for k to choose from.
Similarly f(4) = f(3) * 7 = 9 * 9 * 8 * 7....
...
f(10) = 9 * 9 * 8 * 7 * 6 * ... * 1
f(11) = 0 = f(12) = f(13)....
any number with length > 10 couldn't be unique digits number.
The problem is asking for numbers from 0 to 10^n. Hence return f(1) + f(2) + .. + f(n)
class Solution {
public int countNumbersWithUniqueDigits(int n) {
if (n == 0) return 1;
int res = 10;//n = 1时
int availableNumber = 9;
int uniqueDigit = 9;
while(n -- > 1 && availableNumber >= 1){
uniqueDigit *= availableNumber;
res += uniqueDigit;
availableNumber --;
}
return res;
}
}