LintCode 用递归打印数字

本文介绍了一种使用递归算法来找出并打印从1到最大的N位整数的方法。通过字符串模拟数字的方式,实现了一个C++类,该类能够递归地生成所有可能的N位数,并将其存储在一个整数数组中返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

中等 用递归打印数字
24%
通过

用递归的方法找到从1到最大的N位整数。

您在真实的面试中是否遇到过这个题? 
Yes
样例

给出 N = 1, 返回[1,2,3,4,5,6,7,8,9].

给出 N = 2, 返回[1,2,3,4,5,6,7,8,9,10,11,...,99].

用字符串模拟数字

class Solution {
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> res;
        if (n ==0) {
            return res;
        }
        char *num = new char[n+1];
        num[n] = '\0';
        for (int i = 0; i < 10; ++i) {
            num[0] = i + '0';
            recursion(num,n,0,res);
        }
        delete [] num;
        return res;
    }
    void recursion(char * num,int length,int index,vector<int>& res) {
        if (index == length-1) {
            int a = atoi(num);
            if(a != 0) {
            res.push_back(a);    
            }
            return;
        }
        for (int i=0; i< 10; i++) {
            num[index + 1] = i +'0';
            recursion(num,length, index+1 ,res);
            
        }
        return;
    }
};


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值