Yang hui triangle
Given a non-negative integer numRows, generate the former numRows of a Yanghui triangle.
In Yang Hui’s triangle, each number is the sum of the numbers on its upper left and upper right.
Examples can be found on the LeetCode website.
Source: LeetCode link: leetcode-cn.com/problems/pa… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Solution 1: brute force cracking method
First, when numRows is equal to 1 or 2, return the first two fixed rows.
When numRows is greater than or equal to 3, processing begins at line 3, assuming the current row is cur and the previous row is last:
- The first number in cur is 1;
- The second digit from cur to the penultimate digit (j) is the sum of the corresponding positions on the last line (J-2 and J-1);
- The last digit of cur is 1;
- Add cur to result set result.
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(); }}}Copy the code
【 Daily Message 】 To see the world with a clean heart, to live with a happy heart, to feel normal heart, to remove obstacles with a soft heart.