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.
class Solution {
public:
vector<int> ans;
vector<int> lexicalOrder(int n)
{
for(int i=1; i<=9; i++)
dfs(i, n);
return ans;
}
void dfs(int cur, int n)
{
if(cur > n)
return;
ans.push_back(cur);
for(int i=0; i<=9; i++)
if(cur * 10 + i <= n)
dfs(cur * 10 + i, n);
}
};