Yang hui triangle

NumRows = NumRows = NumRows = NumRows = NumRows = NumRows = NumRows = NumRows = NumRows

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 equals 1 or 2, it returns the first two rows fixed.

When numRows is greater than or equal to 3, start processing on row 3, 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;
  • Add cur to result set result.

Finally, result is returned.

import java.util.ArrayList; import java.util.List; public class LeetCode_118 { public static List<List<Integer>> generate(int numRows) { List<List<Integer>> result = new ArrayList<>(); List<Integer> one = new ArrayList<>(); one.add(1); result.add(one); if (numRows == 1) { return result; } List<Integer> two = new ArrayList<>(); two.add(1); two.add(1); result.add(two); if (numRows == 2) { return result; } for (int i = 3; i <= numRows; i++) { List<Integer> lastOne = result.get(result.size() - 1); List<Integer> cur = new ArrayList<>(); cur.add(1); for (int j = 2; j < i; j++) { cur.add(lastOne.get(j - 2) + lastOne.get(j - 1)); } cur.add(1); result.add(cur); } return result; } public static void main(String[] args) { for (List<Integer> integers : generate(5)) { for (Integer integer : integers) { System.out.print(integer + " "); } System.out.println(); }}}

【 Daily Message 】
To see the world with a pure heart, to live with a joyful heart, to create affection with a normal heart, to remove obstacles with a soft heart.