原题链接:Leetcode 357. Count Numbers with Unique Digits
Given an integer n
, return the count of all numbers with unique digits : x
, where 0 <= x < 10n.
Example 1:
Input: n = 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99
Example 2:
Input: n = 0
Output: 1
Constraints:
- 0 <= n <= 8
解法一:组合数学
思路:
首先可以罗列一下n取不同值的情况:
- 0 对应 1(x只能为1)
- 1 对应 10(x可以取0~9)
- 2 对应 9 * 9(第一位排除先导0可以取9种情况,第二位和第一位不同,可以取9种情况)
- 3 对应 9 * 9 * 8(前两位和上面相同,第三位要排除前两位取得情况)
- 4 对应 9 * 9 * 8 * 7(以此类推)
- 5 对应 9 * 9 * 8 * 7 * 6
- 6 对应 9 * 9 * 8 * 7 * 6 * 5
- 7 对应 9 * 9 * 8 * 7 * 6 * 5 * 4
- 8 对应 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3
对于n>=2的情况,还要再加上n=1时候的十种才是正确的答案
因此当n>=2时,有公式:
a n s = 9 ∗ A 9 d − 1 ans = 9 * A_{9}^{d-1} ans=9∗A9d−1
c++代码:
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if(n == 0)
return 1;
if(n == 1)
return 10;
int ans = 10, cur = 9;
// 从第二位开始
for (int i = 2; i <= n; ++i) {
cur *= 9 - i + 2;
ans += cur;
}
return ans;
}
};
复杂度分析:
- 时间复杂度:O(n),一趟循环
- 空间复杂度:O(1)