第十周作业:
357. Count Numbers with Unique Digits
解题思路:
357. Count Numbers with Unique Digits
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-9, 10个数字,从左到右第一位不能是0,只能在0-9中选一个,第二位则可以在剩下9个中选,然后剩下8个。。。并且要数位少一位的情况,比如5位数包括了4位数,3位数以及2位数和1位数的结果。
代码如下:
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
int result = 1, num = 9;
if (n) {
result = 10;
for (int i = 2; i <= n; i++) {
num *= (9 - i + 2);
result += num;
}
}
return result;
}
};