Yang Hui Triangle (various ways of writing)

Write a program to generate a Yang Hui triangle with a given number of rows
      1
    1 1 
   1 2 1 
  1 3 3 1 
 1 4 6 4 1 
1 5 10 10 5 1

Creating an Array Through observation, a Yang Hui triangle is actually a two-dimensional array with a different number of columns in each row, and the number of columns in the i-th row is actually i. Based on this, we can first construct a Yang Hui triangle with a different number of columns.

1. Initialize the border

The first number and the last number in each row are both 1, so here we can use a loop to set the first number and the last number in each row in the array just created to 1.

2. Improve internal

Starting from the third level, the value of the jth number inside is equal to the sum of the value of the j-1th number in the previous row plus the value of the jth number. That is, a[i][j] = a[i-1][j-1]+a[i-1][j].

3. Code

   int nums = 6;
        int[][] arr = new int[nums][];
        for (int i = 0; i < nums; i++) {
            arr[i] = new int[i + 1];
            arr[i][0] = 1;
            arr[i][i] = 1;
//初始化边框
        }
//        for (int i = 0; i < nums; i++) {
//            arr[i][0] = 1;
//            arr[i][i] = 1;
//        }
        //完善内部
        for (int i = 0; i < nums; i++) {
            for (int j = 1; j < i; j++) {
                arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
            }
        }
        //输出
        for (int i = 0; i < nums; i++) {
            for (int k = nums - i - 1; k > 0; k--) {
                System.out.print(" ");
            }
            for (int j = 0; j <= i; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }

The second method 

  int[][] nums = new int[6][];

        for (int i = 0; i < nums.length; i++) {
            nums[i] = new int[i + 1];
            for (int j = 0; j < nums[i].length; j++) {
                if (j == 0 || j == nums[i].length - 1) {
                    // 第一个和最后一个
                    nums[i][j] = 1;
                } else {
                    nums[i][j] = nums[i - 1][j] + nums[i - 1][j - 1];
                }
            }
        }


        for (int i = 0; i < nums.length; i++) {
            System.out.println(Arrays.toString(nums[i]));
        }
    }
}

Guess you like

Origin blog.csdn.net/pachupingminku/article/details/132208788