java - 以金字塔形式递归添加数字
问题描述
我有这个给定的数组{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
我想我在使用递归时必须使用堆栈。但我不知道怎么做。
解决方案
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);
}
}
}
推荐阅读
- java - 按下后退按钮时,上一个片段显示空白屏幕(使用多个片段事务)
- android-studio - Android Studio IDE 代码补全建议
- mysql - MySQL:加入 OR 子句会变慢
- node.js - 用 Puppeteer 数年
- python - 如何使用 Prophet 绘图功能在 x 轴上显示小时数
- spreadsheetgear - 如何检测 SpreadsheetGear 中的缺失列
- python - 在 Windows 和 NEOS 服务器上的 Python 中使用 IPOPT 时出错
- json - 使用私有设置器反序列化 JSON
- node.js - 第一次尝试连接到 mongodb 时出错
- python - 如何创建包含特征选择和 KerasClassifier 的 sklearn 管道?GridSearchCV 期间 input_dim 更改的问题