357. Count Numbers with Unique Digits
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
// Math + Dynamic Programming
int countNumbersWithUniqueDigits(int n) { // time: O(1); space: O(1)
if (n == 0) return 1;
int res = 10, uniq = 9, avai = 9;
while (n-- > 1 && avai > 0) {
uniq *= avai;
res += uniq;
--avai;
}
return res;
}
Last updated
Was this helpful?