leetcode_357 Count Numbers with Unique Digits


  • 題意分析:非負の整数nを与えて、0<=x<10^nの中で求めて、どれだけのビットの上の数字が互いに異なる数がありますか?n=2の場合、範囲は[001]であり、91個の数(11,22,33,44,55,66,77,88,99を除く).
  • 解題構想:統計法則は以下の通り:
    i = 1 ,10 
    i = 2 ,10  + 9*9 
    i = 3 ,10  + 9*9  + 9*9*8 
    i = 4 ,10  + 9*9  + 9*9*8  + 9*9*8*7 
    ......
    i = n ,10  + 9*9  + 9*9*8  + 9*9*8*7  + ... + 9*9*8*7*...*(9-i+2)
    
    以上の分析に基づいて、プログラムを作成して実現することができる.
  • C++実装
    //        
    int countNumbersWithUniqueDigits1(int n)
    {
        if (n == 0)
            return 1;
        int result = 10;
        if (n == 1)
            return result;
        int temp = 9;
        for (int i = 2; i <= n; i++)
        {
            temp = temp * (9 - i + 2);
            result += temp; 
        }
        return result;
    }
    //           (        )
    int countNumbersWithUniqueDigits(int n) 
    {
        n = min(n, 10);
        int *p = new int[n+1];
        for (int i = 0; i <= n; i++)
        {
            p[i] = 9;
        }
        p[0] = 1;
        for (int i = 2; i <= n; i++)
        {
            for (int x = 9; x >= 9 - i + 2; x--)
            {
                p[i] *= x;
            }
        }
        int result = 0;
        for (int i = 0; i <= n; i++)
            result += p[i];
        return result;
    }
    
  • Java実装
    //     
    public int countNumbersWithUniqueDigits(int n) {
        if (n == 0)
            return 1;
        if (n == 1)
            return 10;
        int result = 10;
        int temp = 9;
        for (int i = 2; i <= n; i++) {
            temp *= (9 - i + 2);
            result += temp;
        }
        return result;
    }
    //           (        )
    public int countNumbersWithUniqueDigits(int n) {
        if (n == 0)
            return 1;
        if (n == 1)
            return 10;
        int [] p = new int[n + 1];
        for (int i = 0; i <= n; i++)
            p[i] = 9;
        int result = 0;
        p[0] = 1;
        for (int i = 2; i <= n; i++) {
            for (int x = 9; x >= 9 - i + 2; x--) {
                p[i] *= x;
            }
        }
        for (int i = 0; i <= n; i++) {
            result += p[i];
        }
        return result;
    }
    
  • 参考文献https://www.hrwhisper.me/leetcode-count-numbers-unique-digits/