用递归打印数字
题目
用递归的方法找到从1到最大的N位整数。
注意事项
用下面这种方式去递归其实很容易:
recursion(i) {
if i > largest number:
return
results.add(i)
recursion(i + 1)
}
样例
给出 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].挑战
用递归完成,而非循环的方式。
题解
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) {
List<Integer> result = new ArrayList<Integer>();
find(result,n,0);
return result;
}
private void find(List<Integer> list, int n, int count)
{
if(n==0)
{
if(count>0)
{
list.add(count);
}
return;
}
for(int i=0; i<=9; i++)
{
find(list,n-1,count*10+i);
}
}
}
Last Update 2016.11.8