Print Numbers by Recursion

Print numbers from 1 to the largest number with N digits by recursion.

 Notice

It's pretty easy to do recursion like:

recursion(i) {
    if i > largest number:
        return
    results.add(i)
    recursion(i + 1)
}

however this cost a lot of recursion memory as the recursion depth maybe very large. Can you do it in another way to recursive with at most N depth?

Example

Given N = 1, return [1,2,3,4,5,6,7,8,9].

Given N = 2, return [1,2,3,4,5,6,7,8,9,10,11,12,...,99].

分析:

我们可以按“层”打印,什么意思呢?

第一层 1 - 9  = 1 to (pow(10, 1) - pow(10, 0)) 

第二层: 10 - 99 = 10 to (pow(10, 2) - pow(10, 1)) 

第三层: 100 - 999 = 100 to (pow(10, 3) - pow(10, 2)) 

... 

看到规律了吧。

 1 public class Solution {
 2     /**
 3      * @param n: An integer.
 4      * return : An array storing 1 to the largest number with n digits.
 5      */
 6     public List<Integer> numbersByRecursion(int n) {
 7         List<Integer> list = new ArrayList<Integer>();
 8         if (n <= 0) return list;
 9         // start[0] refers to the start number for the current levevl.
10         // start[1] refers to the exponent.
11         int[] start = {1, 1};
12         helper(n, list, start);
13         return list;
14     }
15     
16     public void helper(int n, List<Integer> list, int[] start) {
17         if (n == 0) return;
18         for (int i = 1; i <= (int)(Math.pow(10, start[1]) - Math.pow(10, start[1] - 1)); i++) {
19             list.add(start[0]++);
20         }
21         start[1]++;
22         helper(n - 1, list, start);
23     }
24 }

 

 

posted @ 2016-07-16 01:37  北叶青藤  阅读(226)  评论(0编辑  收藏  举报