杨辉三角
1. 递归方法
package sort;
/**
* @author WangXiaoeZhe
* @Date: Created in 2019/11/22 13:04
* @description:
*/
public class YangHuiF {
public static int fun(int i, int j) {
if (j == 1 || i == j) {
return 1;
} else {
return fun(i - 1, j) + fun(i - 1, j - 1);
}
}
public static void main(String[] args) {
/**
* 打印的行数
*/
int length = 6;
for (int i = 1; i <= length; i++) {
/**
* 打印空格
*/
for (int j = 1; j <= length - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.printf("%4d", fun(i, j));
}
System.out.println();
}
}
}
2.非递归方法
package sort;
/**
* @author WangXiaoeZhe
* @Date: Created in 2019/11/22 13:22
* @description:
*/
public class YangHui {
/**
* 非递归的方法
*
* @param args
*/
public static void main(String[] args) {
int length = 6;
int[][] arr = new int[length][];
for (int i = 0; i < arr.length; i++) {
arr[i] = new int[i + 1];
for (int j = 0; j < arr.length - i - 1; j++) {
System.out.print(" ");
}
for (int j = 0; j < arr[i].length; j++) {
if (j == 0 || arr[i].length - 1 == j) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];
}
System.out.printf("%4d", arr[i][j]);
}
System.out.println();
}
}
}