字典序排数

85 阅读1分钟

leetcode: 386. 字典序排数

题目描述

给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。

你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。

示例

输入: n = 13
输出: [1,10,11,12,13,2,3,4,5,6,7,8,9]

解题思路

字典序排数,需要以每位的数值大小做比对 而不是按照这个数大小做比对。

e.g. 191。字典序排数为1、10、100、101、...、109、11、110...

关键节点/操作:

  • *10
  • 字典序 尾巴为9
  • n

image.png

使用栈,就每次将 [xx9, ..., xx0]存入 取栈顶元素。

完整代码:

  • dfs

    class Solution {
        public List<Integer> lexicalOrder(int n) {
            List<Integer> res = new ArrayList<>();
            for (int i = 0, curr = 1; i < n; i++) {
                res.add(curr);
                if (curr * 10 <= n) {
                    curr *= 10;
                }
                else {
                    while (curr % 10 == 9 || curr >= n) curr /= 10;
                    curr++;
                }
            }
            return res;
        }
    }
    
  • class Solution {
        public List<Integer> lexicalOrder(int n) {
            List<Integer> res = new ArrayList<>();
    
            Deque<Integer> stk = new ArrayDeque<>();
            for (int i = 9; i > 0; i--) {
                if (i <= n) {
                    stk.addFirst(i);
                }
            }
    
            while (!stk.isEmpty()) {
                int curr = stk.removeFirst();
                res.add(curr);
                for (int i = 9; i >= 0; i--) {
                    int next = curr * 10 + i;
                    if (next <= n) {
                        stk.addFirst(next);
                    }
                }
            }
    
            return res;
        }
    }