Yang Hui Triangle II

Description: Given a non-negative index k, where k ≤ 33, return the KTH row of the Yanghui Triangle.

In the Yang Hui Triangle, each number is the sum of the numbers at the upper left and the upper right of it.

See the LeetCode website for an example.

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

Solution one: violence crack law

First, when NumRows is equal to 0 or 1, it returns the first two rows fixed.

When numRows is greater than or equal to 2, start processing on row 2, if current row is cur, last row is last:

  • The first number for cur is 1;
  • The second digit of cur to the penultimate digit (j) is the sum of the corresponding positions in the last row (j-2 and j-1);
  • The last number of 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 + " "); }}}

【 Daily Message 】
May you not be angry all day long when you have too little; May you not be in constant fear when you have too much.