Share my C++ solution according to the hint


  • 0
    V
    class Solution {
    public:
        int countNumbersWithUniqueDigits(int n) {
            if (n == 0)
                return 1;
                
            int ret = 10;
            int count = 9;
            int i = 0;
            
            for (i = 2; i <= n; i++)
            {
                count *= (11 - i);
                ret += count;
            }
            
            return ret;
        }
    };

  • 0
    W

    This was the best I could do. I spent a long time trying to fuck around with std::set and std::list but couldn't find a way to make it any faster. Sigh I suck at this stuff.

    #include <string>
    
    class Solution {
    public:
        int countNumbersWithUniqueDigits(int n) {
            int count = 0;
            std::string s;
            
            for (long int i = 0; i < static_cast<long int>(std::pow(10, n)); ++i)
            {
                s = std::to_string(i);
                std::sort(s.begin(), s.end());
                auto iter = std::adjacent_find(s.begin(), s.end());
                if (iter == s.end()) { ++count; }   
            }
            
            return count;
        }
    };
    

Log in to reply
 

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