Leetcode - Lexicographical Numbers

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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/c6da053c894e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞