lintcode-medium-Print Numbers by Recursion

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Print Numbers by Recursion相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

特殊写法

C语言中 num3=(num1=34,num2++,num1+num2++)解释下啥意思

C语言新手 num=num1+num2/num3-num4; 请问那个句子应该怎么读呢?而且我还

C语言中num++啥意思

实现两个数字的交换(C语言)

c语言中 num2&&(ret_num=func(num2,num1%num2)) 是啥意思???