package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.com/problems/lexicographical-numbers/
 */
public class Problem386 {
    public List<Integer> lexicalOrder(int n) {
        List<Integer> result = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            lexicalOrder(n, "" + i, result);
        }
        return result;
    }

    private void lexicalOrder(int n, String accu, List<Integer> result) {
        int num = Integer.parseInt(accu);
        if (num > n) {
            return;
        }
        result.add(num);
        for (int i = 0; i <= 9; i++) {
            lexicalOrder(n, accu + i, result);
        }
    }

    public static void main(String[] args) {
        Problem386 prob = new Problem386();
        System.out.println(prob.lexicalOrder(13));
        System.out.println(prob.lexicalOrder(5000));
        System.out.println(prob.lexicalOrder(5000000));
    }
}

@@ -308,30 +308,104 @@
     
-lexicalOrder(n, %22%22 + i
+if (i %3E n) %7B%0A                break;%0A            %7D%0A            lexicalOrder(n, 1, 1, new IntRef()
 , re
@@ -447,24 +447,86 @@
 ult;%0A    %7D%0A%0A
+    private static class IntRef %7B%0A        int counter;%0A    %7D%0A%0A
     private 
@@ -554,20 +554,45 @@
  n, 
-String
+int multiplier, int
  accu,
+ IntRef ref,
  Lis
@@ -629,35 +629,36 @@
 nt n
-um = Integer.parseInt(
+ewNumber = multiplier * 
 accu
-)
 ;%0A  
@@ -668,18 +668,24 @@
    if (n
-um
+ewNumber
  %3E n) %7B%0A
@@ -718,33 +718,8 @@
   %7D%0A
-        result.add(num);%0A
     
@@ -769,41 +769,35 @@
     
-lexicalOrder(n, accu + i, result)
+int newAccu = newNumber + i
 ;%0A  
@@ -806,265 +806,212 @@
     
-%7D%0A
     
-%7D%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem386 prob = new Problem386();%0A        System.out.println(prob.lexicalOrder(13));%0A        System.out.println(prob.lexicalOrder(5000));%0A        System.out.println(prob.lexicalOrder(5000000));
+if (newAccu %3E n %7C%7C ref.counter == n) %7B%0A                break;%0A            %7D%0A            result.add(newAccu);%0A            ref.counter++;%0A            lexicalOrder(n, 10, newAccu, ref, result);%0A        %7D
 %0A   

Solve problem 386