0-ms 10-line Java solution in O(1) space (No-backtrack no-DP)


  • 1
    R
        public int countNumbersWithUniqueDigits(int n) {
            int totalCount = 1;        
            for(int i = 1; i <= n; i++)
            {
                int j = i, digit = 9, count = 1;           
                while(j-- > 1) {  count *= digit--; }            
                totalCount += 9*count;
            }        
            return totalCount;
        }
    

  • 0
    B

    @ros62 This is very elegant. Basically you count all possible n digits and all possible n-1 digits and all possible n-2 digits number. I really like it.


Log in to reply
 

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