My code:
public class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> ret = new ArrayList<Integer>();
if (n <= 0) {
return ret;
}
for (int i = 1; i < 10; i++) {
helper(i, n, ret);
}
return ret;
}
private void helper(int num, int n, List<Integer> ret) {
if (num > n) {
return;
}
else {
ret.add(num);
for (int i = 0; i < 10; i++) {
if (10 * num + i > n) {
return;
}
helper(10 * num + i, n, ret);
}
}
}
}
reference:
https://discuss.leetcode.com/topic/55377/simple-java-dfs-solution
看的是这个DFS的解法。
比较好懂。
还有一个 iteration 的解法,没怎么看懂,速度更快些。
https://discuss.leetcode.com/topic/55184/java-o-n-time-o-1-space-iterative-solution-130ms
Anyway, Good luck, Richardo! — 10/13/2016