# 357 Count Numbers with Unique Digits

## 357. [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/description/)

## 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**

```java
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**

```java
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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/backtracking/357-count-numbers-with-unique-digits.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
