问题描述:
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.
问题分析:
根据题意,我们可以考虑如下做法,先把1开头的所有值求出,然后再求2,3,...,9开头的值。这个地方我们可能就要用递归来实现我们的算法了。
过程详见代码:
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> res;
bl(res, log10(n), 0, n, 0);
return res;
}
void bl(vector<int>& res, int maxDepth, int depth, int n,int cur)
{
if (depth > maxDepth) return;
int i;
if (!depth) i = 1;
else i = 0;
for (; i <= 9; i++)
{
if (cur * 10 + i <= n)
{
res.push_back(cur * 10 + i);
bl(res, maxDepth, depth + 1, n, cur * 10 + i);
}
else return;
}
}
};