class Solution {
private void add(List<Integer> res, int m, int n) {
if (m > n) return;
if (m != 0) {
res.add(m);
for (int i = 0; i <= 9; i++) {
add(res, m * 10 + i, n);
}
} else {
for (int i = 1; i <= 9; i++) {
add(res, i, n);
}
}
}
public List<Integer> lexicalOrder(int n) {
List<Integer> res = new ArrayList<>();
if (n == 0) return res;
add(res, 0, n);
return res;
}
}
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> list = new ArrayList<>(n);
int curr = 1;
for (int i = 1; i <= n; i++) {
list.add(curr);
if (curr * 10 <= n) {
curr *= 10;
} else if (curr % 10 != 9 && curr + 1 <= n) {
curr++;
} else {
while ((curr / 10) % 10 == 9) {
curr /= 10;
}
curr = curr / 10 + 1;
}
}
return list;
}
}
public class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> res = new ArrayList<>();
for(int i=1;i<10;++i){
dfs(i, n, res);
}
return res;
}
public void dfs(int cur, int n, List<Integer> res){
if(cur>n)
return;
else{
res.add(cur);
for(int i=0;i<10;++i){
if(10*cur+i>n)
return;
dfs(10*cur+i, n, res);
}
}
}
}