我正在尝试创建一个递归方法,将Pascal的三角形打印为颠倒和正面。我想使用布尔变量在倒三角形和右侧三角形之间切换。到目前为止,我已成功编写代码以使pascal的三角形颠倒:
public class Main
{
boolean upsideDown = true;
public void printPascal(int n)
{
if(!upsideDown)
{
//THIS IS WHERE I'M STUCK
}
if (upsideDown)
{
if(n < 0)
return;
for (int k = 0; k <= n; k++)
{
System.out.print(binom(n, k) + " ");
}
System.out.println();
printPascal(n - 1);
}
}
public int binom(int n, int k)
{
if (k==n || k==0)
return 1;
else return binom(n-1,k-1) + binom(n-1, k);
}
public static void main(String[] args)
{
new Main().printPascal(10); //This will print the Pascal's triangle
//from levels 10 to 0
}
}
所以现在,我正试图将Pascal的三角形正面朝上打印(从0级到10级)。如何制作实现此目的的递归方法?
我知道网上有很多关于Pascal三角形的代码。但我找不到任何特别针对我的问题的事情。
答案 0 :(得分:2)
似乎最优雅的解决方案是更改打印顺序,以便首先打印最后一步,然后打印倒数第二步,最后打印第一步。这会有用吗?
public void printPascal(int n) {
if(!upsideDown)
{
if(n < 0)
return;
//print the future step first, then print current step
printPascal(n - 1);
System.out.println();
for (int k = 0; k <= n; k++)
{
System.out.print(binom(n, k) + " ");
}
}
if (upsideDown)
{
if(n < 0)
return;
for (int k = 0; k <= n; k++)
{
System.out.print(binom(n, k) + " ");
}
System.out.println();
printPascal(n - 1);
}
}
答案 1 :(得分:1)
您可以迭代用帕斯卡三角形创建一个二维数组,然后将其打印在左上角,如下所示:
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
代码:
int n = 10;
// an array of 'n' rows
int[][] triangle = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
triangle[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
triangle[i][j] = 1;
else
// all other elements are the sum of the
// previous element in the row and column
triangle[i][j] = triangle[i][j - 1] + triangle[i - 1][j];
}
// output
for (int[] row : triangle) {
for (int element : row)
// format as a two-digit number
System.out.printf("%2d ", element);
System.out.println();
}
答案 2 :(得分:0)
这是前两个答案的总结,在这里我们可以输入帕斯卡三角形中所需的必要行数。
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Main
{
boolean upsideDown = true;
public void printPascal(int n)
{
if(!upsideDown)
{
if(n < 0)
return;
printPascal(n - 1);
System.out.println();
for (int k = 0; k <= n; k++)
{
System.out.print(binom(n, k) + " ");
}
}
if (upsideDown)
{
if(n < 0)
return;
for (int k = 0; k <= n; k++)
{
System.out.print(binom(n, k) + " ");
}
System.out.println();
printPascal(n - 1);
}
}
public int binom(int n, int k)
{
if (k==n || k==0)
return 1;
else return binom(n-1,k-1) + binom(n-1, k);
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
new Main().printPascal(number-1);
}
}