357 Count Numbers with Unique Digits

1. Question

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

2. Implementation

(1) Backtracking

class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        boolean[] used = new boolean[10];
        int[] count = new int[1];
        getNumbersWithUniqueDigits(0, n, used, count);
        // 加1因为要算上刚开始的0 
        return 1 + count[0];
    }

    public void getNumbersWithUniqueDigits(int curLevel, int depth, boolean[] used, int[] count) {
        if (curLevel == depth) {
            return;
        }

        int start = curLevel == 0 ? 1 : 0;

        for (int i = start; i < 10; i++) {
            if (!used[i]) {
                used[i] = true;
                ++count[0];
                getNumbersWithUniqueDigits(curLevel + 1, depth, used, count);
                used[i] = false;
            }
        }
    }
}

(2) DP

class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if (n > 10) {
            return 0;
        }

        int[] dp = new int[11];
        // 0个digit的时候,unique number是1, 这里我们把0当做
        dp[0] = 1;
        dp[1] = 9;

        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] * (9 - i + 2);
        }

        int res = 0;
        for (int i = 0; i <= n; i++) {
            res += dp[i];
        }
        return res;
    }
}

3. Time & Space Complexity

Backtracking: 时间复杂度O(n!), 如果n > 10的话,时间复杂度为O(10!), 空间复杂度O(n)

DP: 时间复杂度O(n), 空间复杂度O(1)

Last updated