386. Lexicographical Numbers

40 阅读1分钟

image.png

方法 dfs

image.png

迭代

class Solution {
    public List<Integer> lexicalOrder(int n) {
        List<Integer> res = new ArrayList<>();
        int cur = 1;
        for (int i = 0; i < n; i++) {
            res.add(cur);
            // 如果当前数字乘以10加1仍然小于等于n,尝试增加最后一位
            if (cur * 10 <= n) {
                cur *= 10;
            } else {
                // cur % 10 == 9, cur = 109, n = 300
                // while : cur = 199, n = 300
                // if cur == n: cur = 105, n = 105
                // 当前数字已经达到n或者是一个9结尾的数字,需要回溯
                while (cur % 10 == 9 || cur == n) {
                    cur /= 10;
                }
                // 增加前一位
                cur++;
            }
        }
        return res;
    }
}


递归

class Solution {
    List<Integer> ans = new ArrayList<>();
    public List<Integer> lexicalOrder(int n) {
        for (int i = 1; i <= 9; i++) dfs(i, n);
        return ans;
    }
    void dfs(int cur, int limit) {
        if (cur > limit) return ;
        ans.add(cur);
        for (int i = 0; i <= 9; i++) dfs(cur * 10 + i, limit);
    }
}

给一个数组,返回字典排序