原题链接在这里:https://leetcode.com/problems/count-numbers-with-unique-digits/description/
题目:
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]
)
题解:
f(n)代表n位时有多少number是全用的unique digit的.
f(1) = 10. (0,1,2,3,4,5,6,7,8,9)
f(2) = 9*9. 首位有1到9可选, 二位有0到9除了一位已选的数字可选.
f(3) = f(2)*8. 三位有0到9除了一位二位已选的数字可选.
...
f(10) = f(9)*1.
f(11) = 0 = f(12) = f(13).
最后res是f(1) + f(2) + f(3) + ... + f(n).
Time Complexity: O(n). Space: O(1).
AC Java:
1 class Solution { 2 public int countNumbersWithUniqueDigits(int n) { 3 if(n == 0){ 4 return 1; 5 } 6 7 int res = 10; 8 int uniqueCount = 9; 9 int availableNum = 9; 10 while(n>1 && availableNum>0){ 11 uniqueCount *= availableNum; 12 res += uniqueCount; 13 availableNum--; 14 n--; 15 } 16 return res; 17 } 18 }