Description
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
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⋅9⋅8⋅...⋅(11−i),2≤i≤10.
The the total number of numbers in the range of [0,10n) with unique digits are ∑0≤i≤min(n,10)f(i).
My solution
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
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;
}
};