码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Print Numbers by Recursion

时间:2016-04-04 16:16:25      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

Print numbers from 1 to the largest number with N digits by recursion.

 

 Notice

It‘s pretty easy to do recursion like:

recursion(i) {
    if i > largest number:
        return
    results.add(i)
    recursion(i + 1)
}

however this cost a lot of recursion memory as the recursion depth maybe very large. Can you do it in another way to recursive with at most N depth?

Example

Given N = 1, return [1,2,3,4,5,6,7,8,9].

Given N = 2, return [1,2,3,4,5,6,7,8,9,10,11,12,...,99].

Challenge

Do it in recursion, not for-loop.

 

public class Solution {
    /**
     * @param n: An integer.
     * return : An array storing 1 to the largest number with n digits.
     */
    public List<Integer> numbersByRecursion(int n) {
        // write your code here
        List<Integer> result = new ArrayList<Integer>();
        if(n < 1)
            return result;
        
        if(n == 1){
            for(int i = 1; i <= 9; i++)
                result.add(i);
            return result;
        }
        
        List<Integer> start = numbersByRecursion(n - 1);
        result.addAll(start);
        result.add(result.get(result.size() - 1) + 1);
        
        int factor = 1;
        for(int i = 1; i < n; i++)
            factor *= 10;
        
        for(int i = 1; i <= 9; i++){
            List<Integer> next = new ArrayList<Integer>();
            for(int j = 0; j < start.size(); j++)
                next.add(i * factor + start.get(j));
            
            result.addAll(next);
            if(i < 9)
                result.add(result.get(result.size() - 1) + 1);
        }
        
        return result;
    }
}

 

lintcode-medium-Print Numbers by Recursion

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5352190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!