7 lines simple C++ recursive solution


  • 3
    H

    Just repeatedly try from 1 to 9, 1 -> 10 -> 100 first, and then plus 1 to the deepest number. Take 13 as example:
    1 -> 10 -> (100) -> 11 -> (110) -> 12 -> (120) -> 13 -> (130) -> (14) -> 2 -> (20) ... -> 9 -> (90)

    class Solution {
    public:
        vector<int> lexicalOrder(int n) {
            vector<int> res;
            helper(1, n, res);
            return res;
        }
        
        void helper(int target, int n, vector<int>& res) {
            if (target > n) return;
            res.push_back(target);
            helper(target * 10, n, res);
            if (target % 10 != 9) helper(target+1, n, res);
        }
    };
    

Log in to reply
 

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