題目
用遞歸的方法找到從1到最大的N位整數(shù)。
注意事項(xiàng)
用下面這種方式去遞歸其實(shí)很容易:
recursion(i) {
if i > largest number:
return
results.add(i)
recursion(i + 1)
}
但是這種方式會耗費(fèi)很多的遞歸空間,導(dǎo)致堆棧溢出。你能夠用其他的方式來遞歸使得遞歸的深度最多只有 N 層么?
您在真實(shí)的面試中是否遇到過這個(gè)題? 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].
分析
理解為1到9,乘以n-1個(gè)10的循環(huán)
代碼
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
ArrayList<Integer> res = new ArrayList<>();
num(n, 0, res);
return res;
}
public void num(int n, int ans,ArrayList<Integer> res){
if(n==0){
if(ans>0){
res.add(ans);
}
return;
}
int i;
for(i=0; i<=9; i++){
num(n-1, ans*10+i, res);
}
}
}