【发布时间】:2017-07-02 20:09:11
【问题描述】:
我将尝试使用递归方法将帕斯卡三角形打印到标准输出。我首先制作了一个迭代方法,以了解我希望该方法如何工作。请参阅下面的代码。
/**
* Print Pascal's triangle with PrintOut.
*
* @param n The amount of rows in total
*/
public static void printPascal(int n) {
for (int i = 0; i < n; i++) {
System.out.format("%" + (n - i) * 3 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("% 6d", binom(i, j));
}
System.out.println();
}
}
Javadoc 和 binom 的签名
/**
* Method which calculates the values in Pascal's triangle.
*
* @param n The row of "the place"
* @param k The column of "the place"
* @return A value on "the place" from the triangle
*/
public static int binom(int n, int k)
然后我开始研究递归方法。我不能使用任何类变量进行打印 - 所以我不能使用向量。我不能有任何对象,方法所在的类,两个方法和 main 是我唯一可以实现的方法。 最大的问题是我无法保存 binom 应该使用的变量,因为它们在每次迭代后都会重置。 现在我有了 printPascal 的代码:
if (n < 0) {
return;
}
printPascal(n - 1);
for (int k = 0; k <= n; k++) {
System.out.format("%6d", binom(n, k));
}
System.out.println();
有没有办法让上面的方法更加递归——有没有办法去掉for循环?
【问题讨论】:
标签: java algorithm recursion pascals-triangle