题目链接
思路:递归
分析:首先我们先不看n多大,把他当作无限大。
那么肯定是1,10,11,12,13,,,,19,20,21,,,29
可以看出,我们可以分为9层,每一层分别是1开头,2开头,3开头。。。。9开头
然后在1开头后,后面又可以分为9层,10,12,13,14,,,,,19
即又可以分为10份,即0开头,1开头,2开头,,,,,9开头,
也就对应10,11,12,13,,,,,19。
那么这里已经可以看出递归的规律了。
- 就是每次将这一层的数字加入答案,
- 然后将(这个数字+一个偏移量)*10,然后进入下一层,这个偏移量就是0~9。
然后再来找一下递归的出口,出口很明显就是不能超过n。
代码:
class Solution {
List<Integer> res = null;
public List<Integer> lexicalOrder(int n) {
res = new ArrayList<>(n);
//因为每一批肯定分别是1、2、3、4这种数字开头的,然后在这些数字中间再去插入
for(int i = 1; i<= (n>9?9:n); i++){
res.add(i);
//在i和i+1之间插入数字,那么第一个必定是i*10
helper(n, i*10);
}
return res;
}
/**
*
* @param res 答案列表
* @param n 不能超过这个n
* @param base 这一层最小的一个
*/
public void helper(List<Integer> res, int n, int base){
for(int i=0; i<10; i++){
//在最小的一个又可以细分为10份,但是base+i不能超过n
if(base+i<=n){
//将每一份加入
res.add(base+i);
//然后同理,也是在base+i与 base+i+1之间插入数字
helper(res,n, (base+i)*10 );
}else{
return;
}
}
}
}