【英文】杨辉三角

Foreword

LeetCode answers, using Java language

Problem

Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.ArrayList;
import java.util.List;

class Solution {
public List<List<Integer>> generate(int numRows) {

// Create a numRows*numRows 2D array
int[][] arr = new int[numRows][numRows];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < i+1; j++) {
/*
If it is the first column or the last column, assign it as 1
Otherwise, assign it as the sum of "the number in the same column of the previous row" and "the number in the previous column of the previous row"
*/
if (j==0 || j==i) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i-1][j] + arr[i-1][j-1];
}
}
}

// Put the 2D array into a nested list (discard the placeholder 0 in the 2D array)
List l = new ArrayList();
for (int i = 0; i < numRows; i++) {
List list = new ArrayList();
for (int j = 0; j < i+1; j++) {
list.add(arr[i][j]);
}
l.add(list);
}

return l;
}

}

Done