-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLexicographicalNumbers386.java
43 lines (38 loc) · 1.24 KB
/
LexicographicalNumbers386.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.* ;
public class LexicographicalNumbers386 {
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> result = new ArrayList<>();
for(int i = 1; i <= 9; i++) {
dfs(i, n, result);
}
return result;
}
private void dfs(int i, int n, List<Integer> result) {
if(i > n) return;
result.add(i);
for(int j = 0; j <= 9; j++) {
dfs(i * 10 + j, n, result);
}
}
}
// improve performance : -
class SolutionOptimal {
public List<Integer> lexicalOrder(int n) {
List<Integer> result = new ArrayList<>();
for(int i = 1; i <= 9; i++) {
dfs(i, n, result);
}
return result;
}
private void dfs(int i, int n, List<Integer> result) {
if(i > n) return;
result.add(i);
for(int j = 0; j <= 9; j++) {
int next = i*10 + j ;
if(next <= n) dfs(next, n, result);
else break ;
}
}
}
}