357. Count Numbers with Unique Digits

Question

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n.

Example:

Input: 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

Thinking:

  • Method 1:
    • 通项公式: f(k) = 9 * 9 * 8 * … (9 - k + 2)
class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if(n == 0)  return 1;
        int res = 10, cnt = 9;
        for(int i = 2; i <= n; i++){
            cnt *= 11 - i;
            res += cnt;
        }
        return res;
    }
}