1. 程式人生 > >357. Count Numbers with Unique Digits-- back tacking 或者數學問題

357. Count Numbers with Unique Digits-- back tacking 或者數學問題

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, 
             excluding 11,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; } }