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
10 11-...-19
100-101-..-109 110-112-...-119
1000-1001-...-1009 1010-1011-..1019
先处理左边的,先处理上面的。一样的问题。
public class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> ans=new ArrayList<Integer>();
for(int i=1;i<10;i++){
dfs(ans,n,i);
}
return ans;
}
public void dfs(List<Integer> list, int n, int start){
if(start>n)
return;
list.add(start);
for(int i=0;i<10;i++){
dfs(list,n,start*10+i);
}
}
}