lintcode:Print Numbers by Recursion

504 篇文章 0 订阅
66 篇文章 0 订阅

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

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].

Note

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?


class Solution {
private:

    void numbersByRecursionHelper(int n, vector<int> &retVector)
    {
        if (n == 0)
            return;
            
        numbersByRecursionHelper(n-1, retVector);
        int curSize = retVector.size();
        
        for (int i=pow(10, n-1); i<=9*pow(10, n-1); i+=pow(10,n-1))
        {
            for (int idx=0; idx<curSize; idx++)
            {
                retVector.push_back(i+retVector[idx]);
            }
        }
    }
    
public:
    /**
     * @param n: An integer.
     * return : An array storing 1 to the largest number with n digits.
     */
     
    vector<int> numbersByRecursion(int n) {
        // write your code here
        vector<int> retVector;
        retVector.push_back(0);
        
        numbersByRecursionHelper(n, retVector);

        vector<int> res(retVector.begin()+1, retVector.end());
        
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值