C# - combination logic - no extra space, O(10) worst case


  • 0

    hopefully the code is clear enough without more explanation.

        public int CountNumbersWithUniqueDigits(int n) 
        {
            int total = 0;
            if (n > 10) n = 10;
            for (int i = 0; i <= n; i++) total += CountAt(i);
            return total;
        }
        
        public int CountAt(int digits)
        {
            switch (digits)
            {
                case 0  : return 1;
                case 1  : return 9;
                case 2  : return 9 * 9;
                case 3  : return 9 * 9 * 8;
                case 4  : return 9 * 9 * 8 * 7;
                case 5  : return 9 * 9 * 8 * 7 * 6;
                case 6  : return 9 * 9 * 8 * 7 * 6 * 5;
                case 7  : return 9 * 9 * 8 * 7 * 6 * 5 * 4;
                case 8  : return 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3;
                case 9  : return 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2;
                case 10 : return 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1;
                default : return 0;
            }
        }
    

Log in to reply
 

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