The number of digital computing LeetCode 357 different Java implementation of each digit

357. The respective bits of the digital calculation of the number of different

Given a non-negative integer n, the number of digits of calculation are different numbers x, where 0 ≤ x <10n.

Example:

Input: 2
Output: 91
Explanation: 11,22,33,44,55,66,77,88,99 answer should be removed, all numbers in [0,100) interval.

PS:

    dp[i]=dp[i-1]+(dp[i-1]-dp[i-2])*(10-(i-1));
    加上dp[i-1]没什么可说的,加上之前的数字
   dp[i-1]-dp[i-2]的意思是我们上一次较上上一次多出来的各位不重复的数字。以n=3为例,n=2已经计算了0-99之间不重复的数字了,我们需要判断的是100-999之间不重复的数字,那也就只能用10-99之间的不重复的数去组成三位数,而不能使用0-9之间的不重复的数,因为他们也组成不了3位数。而10-99之间不重复的数等于dp[2]-dp[1]。
   当i=2时,说明之前选取的数字只有
    1位,那么我们只要与这一位不重复即可,所以其实有9(10-1)种情况(比如1,后面可以跟0,2,3,4,5,6,7,8,9)。
    当i=3时,说明之前选取的数字有2位,那么我们需要与2位不重复,所以剩余的
    有8(10-2)种(比如12,后面可以跟0,3,4,5,6,7,8,9)
class Solution {
      public int countNumbersWithUniqueDigits(int n) {
      
        if(n==0)
            return 1;
        int []dp=new int [n+1];
        dp[0]=1;
         dp[1]=10;
        for(int i=2;i<=n;i++)
        {
            dp[i]=dp[i-1]+(dp[i-1]-dp[i-2])*(10-(i-1));
        }
        return dp[n];
    }
}
Released 1476 original articles · won praise 10000 + · views 1.81 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104773311