递归打印Pascal';Java中的s三角形

递归打印Pascal';Java中的s三角形,java,recursion,pascals-triangle,Java,Recursion,Pascals Triangle,我需要做两个递归Java方法来计算二项式(n,k)并打印出n行Pascal三角形。递归计算二进制数没有问题,它工作得很好。但是我如何制作一个递归方法来打印它呢?不允许使用for/while循环 我用两个for循环打印三角形没有问题,但我甚至不知道从哪里开始递归。有什么提示吗?提示:如果你有一行整数,比如 1 3 3 1 通过将两个列表按元素相加,可以生成下一行:一个是在前面加0,另一个是在后面加0 01 3 3 1 133110+ 1 4 6 4 1 因此,请尝试使用ArrayList(例如,

我需要做两个递归Java方法来计算二项式(n,k)并打印出n行Pascal三角形。递归计算二进制数没有问题,它工作得很好。但是我如何制作一个递归方法来打印它呢?不允许使用for/while循环


我用两个for循环打印三角形没有问题,但我甚至不知道从哪里开始递归。有什么提示吗?

提示:如果你有一行整数,比如

1 3 3 1
通过将两个列表按元素相加,可以生成下一行:一个是在前面加0,另一个是在后面加0

01 3 3 1

133110+

1 4 6 4 1


因此,请尝试使用ArrayList(例如,一个ArrayList)在其中存储一行,并根据此想法在每次递归调用中修改此ArrayList。

以下是无需递归或迭代即可打印单行的方法:

private void printRow(List<Integer> row) {
    System.out.println(row);
}    
private void打印行(列表行){
系统输出打印项次(行);
}    
除了打印行之外,还需要一个函数来基于当前行构造下一行。您可以通过在当前行上传递迭代器到递归方法中来实现这一点:

// previous is the previous value we iterated over, initially null.
void constructRow(Integer previous, Iterator<Integer> currentRow, List<Integer> nextRow) {
    if (nextRow.isEmpty()) { 
        // each row must start with a 1
        nextRow.add(1);
        // if there are no more elements in the current row then we are done
        if (!currentRow.hasNext()) {
            return;
        }
    }
    if (currentRow.hasNext()) {
        Integer current = currentRow.next();
        // the first time previous == null, skip the row.add and recurse
        if (previous != null) {
            // add the previous and current value to get the next value
            nextRow.add(previous + current);
        }
        constructRow(current, currentRow, nextRow);
    }
    else {
        // the iteration is done, just add a 1 to the end
        nextRow.add(1);
    }
}
//previous是我们迭代的上一个值,最初为null。
void constructRow(整数previous、迭代器currentRow、列表nextRow){
如果(nextRow.isEmpty()){
//每行必须以1开头
下一步添加(1);
//如果当前行中没有更多的元素,那么我们就完成了
如果(!currentRow.hasNext()){
返回;
}
}
if(currentRow.hasNext()){
整数current=currentRow.next();
//第一次previous==null时,跳过行。添加并递归
如果(上一个!=null){
//将上一个值和当前值相加以获得下一个值
下一步添加(上一步+当前);
}
constructRow(当前、当前行、下一行);
}
否则{
//迭代完成后,只需在末尾添加1
下一步添加(1);
}
}
你可以这样称呼它:

List<Integer> nextRow = new ArrayList<>();
constructRow(null, row.iterator(), nextRow);
List nextRow=new ArrayList();
constructRow(null,row.iterator(),nextRow);

现在你必须想出另一个递归方法来重复调用这个方法,每次打印一行。

开始打印最简单的,理解,然后进行更改以增加复杂性,在谷歌上搜索,你会得到更多是的,我想我首先需要了解如何打印一行,但我甚至不能这样做。我以前从未使用过递归。打印一行不需要递归。我不需要?即使我不被允许使用循环?这个答案与递归无关这不是真的,Ross Drew(-;