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, excluding11,22,33,44,55,66,77,88,99
题意: 给你 n , 求 [0,10^n) 数字中不包含重复数字的数字的个数。
数学解:
1. n =1, 从 0~9 中 选一个 A(10,1) =10;
2. n=2 , 十位从 1~9(最高位不能为0) 选一个,个位从 剩下8个数外加0,一共9个数中选一个 ,9*9 = 81
3. n=3, 三位数的个数 9*9*8
4. n=4, 四位数个数: 9*9*8*7
如果n =3, result3 = 10 + 9*9 + 9*9*8
如果 n=4, result4 = result3+ 9*9*8*7
当 n>10 时,无论什么数字都会有重复数字了,不具备统计意义了。
以下code 可以优化, 不用sums 数组, 当n >10 时,就不再需要继续计算了。
class Solution { public int countNumbersWithUniqueDigits(int n) { if(n==0) return 1; int[] sums= new int[n]; sums[0] = 10; int num = 9; int mutiple = 9; for(int i=1; i<n; i++){ mutiple = mutiple *num; sums[i] = mutiple; num--; } int total = 0; for(int sum: sums) total+=sum; return total; } }