# 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;
    }
};
```
