# Count Numbers with Unique Digits

## Description

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

## Solutions

Let $$f(i)$$ be the number of $$i$$-digit numbers with unique digits.

$$f(0) = 1. f(1) = 10. f(i) = 9 \cdot 9 \cdot 8 \cdot ... \cdot (11 - i), 2 \le i \le 10.$$&#x20;

The the total number of numbers in the range of $$\[0, 10^n)$$ with unique digits are $$\sum\_{0 \le i \le min(n, 10)} f(i)$$.

### My solution

```cpp
class Solution {
public:
    int uniqueDigits(int i){
        int count = 9;
        for(int j = 9; j > 0 && i > 0; --j, --i){
            count *= j;
        }
        return count;
    }
    
    int countNumbersWithUniqueDigits(int n) {
        if(n == 0) return 1;
        int count = 10;
        for(int i = 1; i < min(n, 10); ++i){
            count += uniqueDigits(i);
        }
        return count;
    }
};
```

### More efficient implementation

```cpp
class Solution {
public:
    int uniqueDigits(int i){
        int count = 9;
        for(int j = 9; j > 0 && i > 0; --j, --i){
            count *= j;
        }
        return count;
    }
    
    int countNumbersWithUniqueDigits(int n) {
        if(n == 0) return 1;
        int count = 10;
        int prod = 9;
        for(int i = 1; i < min(n, 10); ++i){
            prod *= (10 - i);
            count += prod;
        }
        return count;
    }
};
```


---

# 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://twchen.gitbook.io/leetcode/dynamic-programming/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.
