Simple JAVA Solution By Recursion


  • 2

    ...

    public List<Integer> lexicalOrder(int n) {
        List<Integer> ans = new ArrayList<>(n);
        
        for (int i = 1; i <= 9 && i <= n; i++) {
            ans.add(i);
            solve(ans, n, i*10);
        }
        
        return ans;
    }
    
    private void solve(List<Integer> ans, int n, int high) {
        for (int i = 0; i <= 9; i++) {
            int newNum = high+i;
            if (newNum > n) return;
            ans.add(newNum);
            solve(ans, n, newNum*10);
        }
    }
    

    ...


Log in to reply
 

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