g0301_0400.s0386_lexicographical_numbers.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0301_0400.s0386_lexicographical_numbers;
// #Medium #Depth_First_Search #Trie #2022_07_13_Time_4_ms_(93.65%)_Space_57.2_MB_(30.81%)
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List lexicalOrder(int n) {
List lst = new ArrayList<>();
dfs(lst, n, 0);
return lst;
}
private void dfs(List lst, int n, int num) {
for (int i = 0; i <= 9; i++) {
int cur = 10 * num + i;
// get rid of 0
if (cur == 0) {
continue;
}
// when larger than n, return to the previous level
if (cur > n) {
return;
}
lst.add(cur);
dfs(lst, n, cur);
}
}
}