[Java practice questions] Output n lines of Yanghui triangle

Hits: 0

1. Title description:

Both sides of Yanghui’s triangle are 1, and the rest of the interior is the sum of the two numbers on the shoulders.

2. Question ideas:

①, the beginning and the end of Yang Hui’s triangle are both 1;

②. The element in the i-th row and the j-th column of the Yanghui triangle is the sum of the element i-1 in the previous row and its previous element. The formula says:

list[i][j] = list[i-1][j]+list[i-1][j-1]

3. Complete code:

public class Test {
    public static void yang (int num) {
        List<List<Integer>> ret = new ArrayList<>(); //A new Arraylist is created here to store each row 
        List<Integer> list1 = new ArrayList<>(); //The Arraylist here is specific to each row 
        list1.add ( 1 ); //the first line is only one 1 ret.add ( list1 );

        for ( int i = 1 ; i < num; i++) {
            List<Integer> list = new ArrayList<>();
            list.add ( 1 ); //The beginning is 1 
            List<Integer> pre = ret.get ( i -1 ); // Use a pre to store the data of the previous row, which is easy to operate for ( int j = 1 ; j < i; j++) { //The second line i and j are both 1 so they will not enter the loop, here is the intermediate processing int num1 = pre. get (j) + pre. get (j -1 ); // The element in row i and column j of Yang Hui's triangle is the sum of the element in the previous row i-1 and the element in the previous column 
                . list.add (num1);


            }
            list.add ( 1 ); //The end is also 1 ret.add ( list) 
            ;
        }
        for (int i = 0; i < ret.size(); i++) {
            System.out.println(ret.get(i));
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        which(num);
    }
}

4. Display of code running results:

You may also like...

Leave a Reply

Your email address will not be published.