换个算法看看
- import java.util.Scanner;
- /**
- * 杨辉三角
- *
- * @author Administrator
- *
- */
- public class YH3J {
- public static void main(String[] args) {
- System.out.print("输入层数:");
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt() + 1;
- int[][] a = new int[n][n];
- a = work(a, n - 1);
- printArray(n, a);
- }
- /*
- * 杨辉三角算法
- */
- public static int[][] work(int[][] a, int n) {
- a[n][0] = 1;
- for (int i = 1; i < n; i++) {
- a[n][i] = work(a, n - 1)[n - 1][i - 1] + work(a, n - 1)[n - 1][i];
- }
- return a;
- }
- /*
- * 遍历数组
- */
- public static void printArray(int n, int[][] a) {
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < i; j++) {
- System.out.print(a[i][j] + "\t");
- }
- System.out.println();
- }
- }
- }
复制代码 |