题目描述
给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。
你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
示例 1:
输入:n = 13
输出:[1,10,11,12,13,2,3,4,5,6,7,8,9]
示例 2:
输入:n = 2
输出:[1,2]
提示:
1 <= n <= 5 * 104
题解
深度优先算法,1)选好开头数字,一直乘以10,直到大于n 2)乘以10后,再遍历加上0-9
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> res = new ArrayList<>();
for (int i = 1; i <= 9; i++) {
orderNum(i, n, res);
}
return res;
}
public void orderNum(int curNum, int maxNum, List<Integer> res) {
if (curNum <= maxNum) {
res.add(curNum);
} else {
return;
}
for (int i = 0; i <= 9; i++) {
orderNum((curNum*10+i), maxNum, res);
}
}
}