C language reconstruction [357] Calculate the number of digits with different digits

Source code for all topics: Git address

topic

给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 ≤ x < 10n 。

示例:

输入: 2
输出: 91 
解释: 答案应为除去 11,22,33,44,55,66,77,88,99 外,在 [0,100) 区间内的所有数字。

Program:

  • This problem can be seen as dp+mathematics, which is the idea of ​​permutation and combination. For n digits, the beginning of 0 is handed over to the next level (n-1 digits), and the remaining direct permutation and combination are enough, and n cannot be greater than 10.
class Solution
{
    
    
public:
    int countNumbersWithUniqueDigits(int n)
    {
    
    
        if (n == 0)
            return 1;
        else if (n == 1)
            return 10;
        else if (n == 2)
            return 91;
        else if (n > 10)
            return countNumbersWithUniqueDigits(10);
        else
        {
    
    
            return countNumbersWithUniqueDigits(n - 1) + 9 * A(9, n - 1);
        }
    }
    int A(int m, int n)
    {
    
    
        //排列组合计算
        if (n == 1)
            return m;
        else
            return m * A(m - 1, n - 1);
    }
};
Complexity calculation
  • Time complexity: O(n)
  • Space complexity: O(1)

Guess you like

Origin blog.csdn.net/symuamua/article/details/114526513