递归方法导致java.lang.StackOverflowError

Recursive method causes java.lang.StackOverflowError

我正在尝试创建帕斯卡三角形,并且行:

return pascalTriangle(row-1, col-1) + pascalTriangle(row-1, col);

在帕斯卡三角形中 returns int 值的递归方法中,导致

Exception in thread "main" java.lang.WhosebugError

它只打印一行1,然后对其他行抛出异常。我需要修复什么才能不抛出任何异常并形成帕斯卡三角形?这是我的代码:

import java.util.Scanner;

/**
 * This program takes n input from the user, and forms
 * Pascal's Triangle in n number of rows that the user entered.
 */
public class DD_PascalsTriangle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter an integer: ");
        // the number of rows created in the Pascal's Triangle
        int n = scanner.nextInt();
        // print Pascal's Triangle
        printTriangle(n);
    }

    /**
     * @param row rows in Pascal's Triangle
     * @param col columns in Pascal's Triangle
     * @return values in the Pascal's Triangle
     */
    private static int pascalTriangle(int row, int col) {
        if (col == 0 || col == row)
            // base case
            return 1;
        else
            // create the values in Pascal's Triangle
            return pascalTriangle(row-1, col-1) + pascalTriangle(row-1, col);
    }

    /**
     * @param n the input from the user, aka the n
     *          number of rows in Pascal's Triangle
     */
    private static void printTriangle(int n) {
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                System.out.println(pascalTriangle(row, col) + " ");
            }
            System.out.println();
        }
    }
}

将第二个循环更改为迭代到 row 而不是 n

public static void printTriangle(int n) {
    for (int row = 0; row < n; row++) {
        for (int col = 0; col <= row; col++) {
            System.out.print(pascalTriangle(row, col) + " ");
        }
        System.out.println();
    }
}

您的代码似乎进入了无限循环,因为您的内循环条件错误。内循环不断迭代并填满栈内存,最终超过了JVM分配的内存量。

为了避免此堆栈溢出错误并完善您的帕斯卡三角形的形状,您可以简单地添加一个额外的循环并更改内循环的条件。

public static void printTriangle(int n) {
    for (int row = 0; row < n; row++) {
        //Added Spacer loop for getting perfect shape for pascal triangle
        for (int spacer = n; spacer > row; spacer--) {
            System.out.print(" ");
        }
        for (int col = 0; col <= row; col++) {
            System.out.print(pascalTriangle(row, col) + " ");
        }
        System.out.println();
    }
}