【问题标题】:Adding numbers with recursion in a pyramid form以金字塔形式递归添加数字
【发布时间】:2021-08-20 19:17:54
【问题描述】:

我有这个给定的数组{1,2,3,4,5},我应该使用递归创建这样的输出:

48
20 28
8 12 16
3 5 7 9
1 2 3 4 5

我必须将[i] 的值与[i+1] 的值相加。最后它应该是一个金字塔的形式。

这是我的代码:

package Übungen;

public class Symmetrie {
    public static void main(String[] args) {
        //0 is just a placeholder to avoid an error in line 21
        int[] b = {1, 2, 3, 4, 5, 0};
        int j = 5;
        reku(b, j);
    }

    public static void reku(int[] num, int j) {
        System.out.println("");
        if (j > 0) {
            for (int i = 0; i < j; i++) {
                System.out.print(num[i] + " ");
                num[i] = num[i] + num[i + 1];
            }
            reku(num, j - 1);
        }
    }
}

它会创建这样的输出:

1 2 3 4 5
3 5 7 9
8 12 16
20 28
48

我认为我在使用递归时必须使用堆栈。但我不知道怎么做。

【问题讨论】:

    标签: java arrays recursion stack


    【解决方案1】:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Collections;
    
    class Main {
        static List<ArrayList<Integer>> listOfLists =
                new ArrayList<ArrayList<Integer>>();
    
        public static void main(String[] args) {
            //0 is just a placeholder to avoid an error in line 21
            int[] b = {1, 2, 3, 4, 5, 0};  
            int j = 5;
    
            reku(b, j);
            Collections.reverse(listOfLists);
            for (List list : listOfLists) {
                System.out.println(list.toString());
            }
        }
    
        public static void reku(int[] num, int j) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            if (j > 0) {
                for (int i = 0; i < j; i++) {
                    list.add(num[i]);
                    //System.out.print(num[i] + " ");
                    num[i] = num[i] + num[i + 1];
                }
                listOfLists.add(list);
                reku(num, j - 1);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 2012-03-27
      相关资源
      最近更新 更多