Yang Hui triangle II

Given a non-negative index K, where k ≤ 33, return row K of yanghui’s triangle.

In Yang Hui’s triangle, each number is the sum of the numbers above its left and above its right.

For details, see the LeetCode official website.

Source: LeetCode link: leetcode-cn.com/problems/pa… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution one: brute force

First, when numRows is equal to 0 or 1, return the first two fixed rows;

When numRows is greater than or equal to 2, processing starts at row 2, if the current row is cur and the previous row is last:

  • The first number in cur is 1;
  • The second digit to the penultimate digit (j) in cur is the sum of the corresponding positions (j-2 and J-1) in the last row;
  • The last number in cur is 1;
  • Set last to cur.

Finally return to cur.

Note: The method is exactly the same as that of leetcode-118-Yang Hui triangle.

import java.util.ArrayList;
import java.util.List;

public class LeetCode_119 {
    public static List<Integer> getRow(int rowIndex) {
        List<Integer> one = new ArrayList<>();
        one.add(1);
        if (rowIndex == 0) {
            return one;
        }
        List<Integer> two = new ArrayList<>();
        two.add(1);
        two.add(1);
        if (rowIndex == 1) {
            return two;
        }
        List<Integer> last = two;
        List<Integer> cur = new ArrayList<>();
        for (int i = 2; i <= rowIndex; i++) {
            cur = new ArrayList<>();
            cur.add(1);
            for (int j = 1; j < i; j++) {
                cur.add(last.get(j - 1) + last.get(j));
            }
            cur.add(1);
            last = cur;
        }
        return cur;
    }

    public static void main(String[] args) {
        for (Integer integer : getRow(3)) {
            System.out.print(integer + ""); }}}Copy the code

May you get too little, not all day long angry; May you have too much and not have to live in fear all day long.