首页 > 解决方案 > 以金字塔形式递归添加数字

问题描述

我有这个给定的数组{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

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

标签: javaarraysrecursionstack

解决方案


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);
        }
    }
}

推荐阅读