c++ recursive solution o(n) time, 149 ms


  • 0
    L

    Idea is that each recursive call adds numbers that start with minPrefix.

    class Solution {
        
    public:
        void recurse(vector<int> &v, int &index, int minPrefix, int max) {
            if (minPrefix > max) {
                return;
            }
            if (minPrefix != 0) {
                v[index++] = minPrefix;
               recurse(v, index, minPrefix*10, max);
            }
    
            for (int i = minPrefix + 1; i < minPrefix + 10 && i <= max; i++) {
                v[index++] = i;
                recurse(v, index, i*10, max);
            }
        }
        
        vector<int> lexicalOrder(int n) {
            vector<int> v (n, 0);
            int index = 0;
            recurse(v, index, 0, n);
            return v;
        }
    };
    

Log in to reply
 

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