LintCode 用递归打印数字
来源:互联网 发布:软件开发解决方案总结 编辑:程序博客网 时间:2024/05/16 15:49
用递归的方法找到从1到最大的N位整数。
样例
给出 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]
.
挑战
用递归完成,而非循环的方式。
方法一:循环输出最大的数为10^n -1
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> ret; int max = 1; for(int i =1; i< n+1; i++){ max *= 10; } for(int j=1; j< max; j++){ ret.push_back(j); } return ret; }};
方法二:递归输出(会溢出)
这种方法,最大值为多少,就递归多少层。当数据比较大时,导致栈溢出
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 int max = 1; for(int i =1; i< n+1; i++){ max *= 10; } return print(max); } vector<int> print(int n){ vector<int> ret; int i =1; if(i <= n){ ret.push_back(i); print(i+1); } return ret; }};
方法三: 递归输出(不溢出)
递归使得递归的深度最多为N。将1-10定为一层,10-100定为一层,那么输入n,最多就循环n层。
class Solution {public: /** * @param n: An integer. * return : An array storing 1 to the largest number with n digits. */ vector<int> ret; //存放数据 vector<int> numbersByRecursion(int n) { // write your code here if( n<1 ){ return ret; } return print(1,n); //打印从1开始的n位数 } vector<int> print(int i, int n){ if( n>=1 ){ //依次将1-9,10-99,100-999放入容器内 int max = i*10; for(int j=i; j<max; j++){ ret.push_back(j); } print(max, n-1); } return ret; }};
0 0
- LintCode-用递归打印数字
- LintCode 用递归打印数字
- lintcode-用递归打印数字
- Lintcode 用递归打印数字
- LintCode 用递归打印数字
- 用递归打印数字-LintCode
- lintcode(371)用递归打印数字
- [LintCode]371.用递归打印数字
- LintCode-剑指Offer-(371)用递归打印数字
- [LintCode] 用递归打印数字 Print Numbers by Recursion
- 用递归打印数字
- 用递归打印数字
- 递归打印数字
- 【递归】数字打印
- 递归打印螺旋数字
- Lintcode 用递归打印从1到N位的最大整数
- 0021利用递归算法打印数字金字塔
- 蓝桥杯常用算法知识点:【递归】数字打印
- iOS -setValue:forKey:和-setObject: forKey区别
- linux的硬链接与软链接
- ios聊天对话显示的UITableView扩展
- 面向对象的OOA、OOD、OOP
- cat命令
- LintCode 用递归打印数字
- Altium Designer使用技巧总结
- Glide使用心得——加载图片出现浅绿色背景问题和Glide加载完成的监听设置
- thrift TSocket read 0 bytes(string类型中的一个坑)
- rsa加密
- FFmpeg内存操作(三)内存转码器
- php 重写
- CodeForces-771D-Bear and Company
- ruby 如何确定数据类型