Recursive to iterative Pascal#39;s triangle(递归到迭代帕斯卡三角形)
问题描述
我想知道如何将递归函数/类转换为迭代函数/类.我已经制作了一个递归帕斯卡三角形,现在需要将其与迭代进行比较.
I wonder how to convert a recursive function/class to an iterative one. I have made a recursive Pascal's triangle, and now need to compare it to an iterative.
public class RecursivePascal extends ErrorPascal implements Pascal {
private int n;
RecursivePascal(int n) throws Exception {
super(n);
this.n = n;
}
public void printPascal() {
printPascal(n, false);
}
public void printPascal(boolean upsideDown) {
printPascal(n, upsideDown);
}
private void printPascal(int n, boolean upsideDown) {
if (n == 0) {
return;
}
if (!upsideDown) {
printPascal(n - 1, upsideDown);
}
for (int i = 0; i < n; i++) {
System.out.print(binom(n - 1, i) + (n == i + 1 ? "
" : " "));
}
if (upsideDown) {
printPascal(n - 1, upsideDown);
}
}
public int binom(int n, int k) {
if (k == 0 || n == k) {
return 1;
}
return binom(n - 1, k - 1) + binom(n - 1, k);
}
}
我需要更改哪些内容才能使其迭代?我仍然有点不确定这是如何工作的.
What do I need to change in order to make it iterative? I'm still a little unsure of how this works.
推荐答案
将下面这两个函数插入到一个pascal类中.我测试了它并且它有效.Prateek Darmwal 发布的那个链接几乎是一回事.
Plug these two functions below into a pascal class. I tested it and it works. That link that Prateek Darmwal posted is pretty much the same thing.
public void nonRecursivePrint() {
nonRecursivePrint(n, true);
}
public void nonRecursivePrint(int n, boolean upsideDown) {
if (!upsideDown) {
for (int j = 0; j < (n + 1); j++) {
for (int i = 0; i < (j); i++) {
System.out.print(binom(j - 1, i) + (j == i + 1 ? "
" : " "));
}
}
} else {
for (int j = n; j > 0; j--) {
for (int i = 0; i < (j); i++) {
System.out.print(binom(j - 1, i) + (j == i + 1 ? "
" : " "));
}
}
}
}
这篇关于递归到迭代帕斯卡三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:递归到迭代帕斯卡三角形
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01