gpt4 book ai didi

java - 如何将其变成帕斯卡三角形而不是直角三角形?

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:42 24 4
gpt4 key购买 nike

我需要一个用于制作帕斯卡三角形的代码。此代码适用于直角三角形,但我需要它是帕斯卡三角形。它需要有 10 行,并且顶部和底部中间有一个间隙。有人可以帮我解决这个问题吗? for 循环就可以了。

public static int get_pascal(int row, int col) {
if (col == 0 || col == row) {
return 1;
} else {
return get_pascal(row - 1, col - 1) + get_pascal(row - 1, col);
}
}

public static void main(String[] args) {
//row size variable
int rowNum = 5;

levels = new String[rowNum];

int i = 0;
int arIndex = 0;
System.out.println(recurseRow(i, rowNum, arIndex));
System.out.println(" ");
System.out.println(upsideDown(rowNum - 1));
}

//Recursion for row
public static String recurseRow(int i, int rowNum, int arrayIndex) {
if (i == rowNum)
return "";
else {
int k = 0;
int next = i + 1;
String str = recurseCol(i, k);
levels[arrayIndex] = str;
arrayIndex += 1;
return str + "\n" + recurseRow(next, rowNum, arrayIndex);
}
}

//Recursion for column
public static String recurseCol(int i, int k) {
if (k > i)
return "";
else {
int next = k + 1;
return get_pascal(i, k) + " " + recurseCol(i, next);
}
}

//upside down recursion
public static String upsideDown(int index) {
if (index < 0) {
return "";
} else {
String str = levels[index];
index -= 1;
return str + "\n" + upsideDown(index);
}
}

最佳答案

帕斯卡三角形 - 是二项式系数的三角形数组,其中第一行和第一列的元素等于 1,所有其他元素是该行和列中前一个元素的总和。

T[i][j] = T[i][j-1] + T[i-1][j];

您可以创建一个迭代方法来填充这样的数组:

public static int[][] pascalsTriangle(int n) {
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the elements of the row
for (int j = 0; j < n - i; j++) {
if (i == 0 || j == 0) {
// elements of the first row
// and column are equal to one
arr[i][j] = 1;
} else {
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
}
}
}
return arr;
}
public static void main(String[] args) {
int n = 10;
System.out.println("n = " + n);
System.out.println("Pascal's triangle:");
int[][] arr = pascalsTriangle(n);
for (int[] row : arr) {
for (int element : row)
System.out.printf("%2d ", element);
System.out.println();
}
}

输出:

n = 10
Pascal's triangle:
1 1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8 9
1 3 6 10 15 21 28 36
1 4 10 20 35 56 84
1 5 15 35 70 126
1 6 21 56 126
1 7 28 84
1 8 36
1 9
1
<小时/>

另请参阅:Array of binomial coefficients

关于java - 如何将其变成帕斯卡三角形而不是直角三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60587257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com