打印杨辉三角。
有2种方法.
第一种使用递归,方法简单,公式如下:
c(x,y)=
1 , (x=1或x=N+1)
c(x-1,y-1)+x(x-1,y) , (其他)
但是缺点是每个数都需要递归,存在很多重复的递归,浪费时间。
public class MakeYanghuiSanjiao {
public static void main(String[] args) {
// 打印N行的杨辉三角
int N = 10;
// 打印各行。m为行号,n为列号,从0开始。
for (int m = 0; m < N; m++) {
for (int n = 0; n <= m; n++) {
System.out.print(c(m, n) + " ");
}
System.out.println();
}
}
public static int c(int m, int n) {
if (n == 0 || n == m) {
return 1;
} else {
return c(m - 1, n - 1) + c(m - 1, n);
}
}
}
第二种使用一个2行的数组存储结果,例如当计算第5行时,数组中存储着第4行的数据。
这样的话,使用了2倍N个int做存储,用空间换取时间。
public class MakeYanghuiSanjiao {
public static void main(String[] args) {
// 打印n行的杨辉三角
int n = 10;
// 使用行为2,列为n的辅助数组,存储运行时的前一行和当前行的结果
int[][] array = new int[2][n];
// 打印各行
for (int i = 0; i < n; i++) {
// 构造第i行的第0个数
array[i%2][0] = 1;
// 构造第i行的第1个到第i个数
for (int j = 1; j < i + 1; j++) {
array[i % 2][j] = array[(i - 1) % 2][j - 1] + array[(i - 1) % 2][j];
}
// 打印第i行
for (int j = 0; j < i + 1; j++) {//第i行的列数是i+1
System.out.print(array[i % 2][j]+" ");
}
System.out.println();
}
}
}
效果:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1