5-line recursive answer in Java with explanation.


  • -1
    H

    with n = 0; answer would be "1"
    with n = 1, we can have "0-9' but not 10
    with n = 2, we have 0-9 plus the two-digits integers without same digits(11,22,33..)
    with n, the new digits we can construct will be the number with n-1 unique digits * how many different digits we can put at the end of these number(which is 10+1-n).
    eg. n = 2, we can have (10+1-2)*(10-1) = 81 2-digits integers without same dights.(10+1-2) digits we can put after each digits we already have(for 1-9)

    eg. n = 3, we can have (10+1-3) = 8 different digits after each 2-digits numbers we already find. that is, 8 * 81 = 648, and the answer for n =3 would be 648+81 = 739 (3-digits integer we constructed + answer for n=2)
    '''
    class Solution {
    public int countNumbersWithUniqueDigits(int n) {
    if(n == 0) return 1;
    if(n == 1) return 10;
    if(n > 10) return countNumbersWithUniqueDigits(10);
    return (countNumbersWithUniqueDigits(n-1) - countNumbersWithUniqueDigits(n-2)) * (11-n) + countNumbersWithUniqueDigits(n-1);
    }
    }
    '''


  • 5
    J

    What is the description of the problem?
    It's hard to read your answer without any information of the problem description


  • 1
    C

    Same with you. Confused a lot.


  • 0
    L

    To the best of my understanding, the problem is that given n >= 0, count the number of n-digit integers with unique digits.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.