无锡市无锡市住房和城乡建设局网站,网站语言,学电子商务有用吗,昆明做网站的公司哪家好题目 用递归打印数字 用递归的方法找到从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]. 注意 用下面这种方式去递归其实很容易#xff1a; recursion(i) {if i largest number:returnresults.add(i)r…题目 用递归打印数字 用递归的方法找到从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]. 注意 用下面这种方式去递归其实很容易 recursion(i) {if i largest number:returnresults.add(i)recursion(i 1)
}但是这种方式会耗费很多的递归空间导致堆栈溢出。你能够用其他的方式来递归使得递归的深度最多只有 N 层么 挑战 用递归完成而非循环的方式 解题 非递归最简单了先求出最大的n位数N然后顺序遍历求解 public class Solution {/*** param n: An integer.* return : An array storing 1 to the largest number with n digits.*/public ListInteger numbersByRecursion(int n) {// write your code hereint N 1;for(int i 1;in;i){N N*10;}N N - 1;ListInteger result new ArrayListInteger();for(int i 1;i N ;i){result.add(i);}return result;}
} Java Code 总耗时: 1629 ms class Solution:# param n: An integer.# return : A list of integer storing 1 to the largest number with n digits.def numbersByRecursion(self, n):# write your code hereN 1for i in range(n):N *10result []for i in range(1,N):result.append(i)return result Python Code 总耗时: 674 ms 给的递归方式运行到74%RunTime Error public class Solution {/*** param n: An integer.* return : An array storing 1 to the largest number with n digits.*/public ListInteger numbersByRecursion(int n) {// write your code hereint N 1;for(int i 1;in;i){N N*10;}N N - 1;ListInteger result new ArrayListInteger();getPrint(1,N,result);return result;}public void getPrint(int i,int N,ListInteger result ){if(iN)return ;result.add(i);getPrint(i1,N,result);}
} Java Code 参考程序来源 public int PrintN(int n,ListInteger res){if(n0){return 1;}int base PrintN(n-1,res);int size res.size();for(int i 1;i 9;i){int subbase base*i;res.add(subbase);for(int j 0;j size ;j){res.add(subbaseres.get(j));}}return base*10;} 上面是关键程序 在求 n-1位数到n位数的时候先求n-2位数到n-1位数就如同下面一样,这个很明显是找规律了。。。 转载于:https://www.cnblogs.com/theskulls/p/4944831.html