1 题目
Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
2 尝试解
2.1 分析
将1-N之间的数字以字典序输出。
考虑1~100,首先输出1开头的数字,1,10,100,11,12,13,14,15,16,17,18,19。即先从节点1开始,向下一层分别处理10~19。处理10时,向下一层先处理100~109,但是由于101已经越界,所以略过,然后处理11,12,13...19。处理完成后,处理节点2。这是典型的深度优先遍历。
2.2 代码
class Solution {
public:
void Add(vector<int>&result,int n,int target){
for(int i = 0; i < (n<10?9:10) && n + i <= target; i++){
result.push_back(n+i);
Add(result,10*(n+i),target);
}
}
vector<int> lexicalOrder(int n) {
vector<int> result;
Add(result,1,n);
return result;
}
};
3 标准解
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> res;
helper(1, n, res);
return res;
}
void helper(int target, int n, vector<int>& res) {
if (target > n) return;
res.push_back(target);
helper(target * 10, n, res);
if (target % 10 != 9) helper(target+1, n, res);
}
};