Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.java
Example:git
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
題目大意:spa
給一個數字n,找出[0,10^n)這個區間內,由不一樣數字組成的數字個數。code
解法:blog
我採用遞歸的解法求解由不一樣數字組成的數字個數,flag這個整數的第0到9位記錄該數字是否被使用過,而tmp則是當前的數字,可是這種解法的效率極低。遞歸
class Solution { int count=1; void dfs(int n,int tmp,int flag){ if (tmp>=Math.pow(10,n)){ return; } for (int i=0;i<10;i++){ if (tmp==0 && i==0) continue; if ((flag&(1<<i))==0 && tmp*10+i<Math.pow(10,n)){ count++; dfs(n,tmp*10+i,flag|(1<<i)); } } } public int countNumbersWithUniqueDigits(int n) { int tmp=0,flag=0; dfs(n,tmp,flag); return count; } }
其實這道題目能夠將問題簡化一些。input
當只有一位數字的時候,有10種結果,f(1)=10。it
當有兩位數字的時候,有9*9種結果,f(2)=9*9。io
當有三位數字的時候,有9*9*8種結果,f(3)=9*9*8。class
java:
class Solution { public int countNumbersWithUniqueDigits(int n) { if (n==0) return 1; int res=10; int a=9,b=9; n--; while (n-->0 && b>0){ a=a*b; res+=a; b--; } return res; } }