[LeetCode] 386. Lexicographical Numbers
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.
You must write an algorithm that runs in O(n) time and uses O(1) extra space.
Example 1:
Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Example 2:
Input: n = 2
Output: [1,2]
Constraints:
1 <= n <= 5 * 104
字典序排数。
给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
思路
思路是 DFS。注意题目要求,是要我们按字典序输出 [1, n] 内所有整数。那么思路就是从 1 到 9,把这九个数字作为第一个 digit,往后面加一个digit,如果不超过 n,就加入结果集。如果超过 n 就不能加。
复杂度
时间O(n)
空间O(1) - required
代码
Java实现,空间O(n)
1 |
|
Java实现,空间O(1)
1 |
|
[LeetCode] 386. Lexicographical Numbers
https://shurui91.github.io/posts/1026628144.html