C++ simple solution with explanation


  • 0

    digit num
    1 ----- 10
    2 ----- 9*9
    3 ----- 9*9*8
    4 ----- 9*9*8*7
    .
    .
    .
    so on

    class Solution {
    public:
        int countNumbersWithUniqueDigits(int n) {
            if (!n) // 10 ^ 0 = 1
                return 1;
            int res = 0, num = 9, i = 9;
            while (--n) {
                num *= i--;
                res += num;
            }
            return res + 10; // 10 for 1 digit
        }
    };
    

Log in to reply
 

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