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])

S: math O(1)

n = 1 时 有10种

n = 2 时有 9 * 9种

n = 3 时有9 * 9 * 8种

n = 4 时有9 * 9 * 8 * 7种

。。。

n > 10时不会有unique digits的数字

    int countNumbersWithUniqueDigits(int n) {
        if (n == 0) return 1;
        int result = 10;
        for (int i = 1; i < min(n, 10); ++i) {
            int count = 1;
            for (int j = 0, choice = 9; j <= i; ++j) {
                count *= choice;
                if (j > 0) choice--;
            }
            result += count;
        }
        return result;
    }

results matching ""

    No results matching ""