[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)
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> res = new ArrayList<>();
for (int i = 1; i <= 9; i++) {
dfs(i, n, res);
}
return res;
}
private void dfs(int cur, int n, List<Integer> res) {
if (cur > n) {
return;
}
res.add(cur);
for (int i = 0; i <= 9; i++) {
int next = cur * 10 + i;
if (next > n) {
break;
}
dfs(next, n, res);
}
}
}
// dfs
Java实现,空间O(1)
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);
if (cur * 10 <= n) {
cur *= 10;
} else {
while (cur % 10 == 9 || cur + 1 > n) {
cur /= 10;
}
cur++;
}
}
return res;
}
}