Elegant Java Recursion (No For Loop At All)


  • 0
    K

    It's so elegant a recursion. No for loop at all. I can't help but post it!

    private void put(List<Integer> ans, int num, int n) {
        ans.add(num);
        if (num * 10 <= n) { put(ans, num * 10, n); } // from 10 to 100, or 11 to 110
        if (num % 10 != 9 && num + 1 <= n) { put(ans, num+1, n); } // from 10 to 11 ... to 19
    }
        
    public List<Integer> lexicalOrder(int n) {
        List<Integer> ans = new ArrayList<Integer>();
        put(ans, 1, n);
        return ans;
    }
    

Log in to reply
 

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