【Leetcode】386. 字典序排数

928 阅读1分钟

题目描述

给定一个整数n, 返回从1到n的字典顺序。

例如,

给定 n =1 3,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9] 。

请尽可能的优化算法的时间复杂度和空间复杂度。 输入的数据n小于等于5,000,000。

题解

先选好首位数字,从1到9,然后再深度优先,一直乘以10,直到数字大于当前值

图解示意:

class Solution {
    public List<Integer> lexicalOrder(int n) {
        List<Integer> ress = new LinkedList<>();
        for (int i = 1; i <= 9; i++) {
            orderImpl(n, i, ress);
        }
        return ress;
    }

    private void orderImpl(int n, int startNum, List<Integer> ress) {
        if (startNum > n) {
            return;
        }
        ress.add(startNum);
        for (int i = 0; i <= 9; i++) {
            if (startNum*10 > n) {
                return;
            }
            orderImpl(n, (startNum*10+i), ress);
        }
    }
}