leetcode-118-easy
Pascal's Triangle
Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
1 <= numRows <= 30
思路一:观察每行的规律,可以发现每一行的 0 和 length-1 固定为 1,其他的位置 i 的值固定为上一行的 i-1 值加上 i 值,完全分类有
- 位置 0, length-1 -> 1
- 位置 i -> pre[i-1] + pre[i]
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> one = new ArrayList<>();
one.add(1);
list.add(one);
List<Integer> pre = one;
for (int i = 2; i <= numRows; i++) {
List<Integer> temp = new ArrayList<>();
for (int j = 1; j <= i; j++) {
if (j == 1 || j == i) {
temp.add(1);
} else {
temp.add(pre.get(j - 1 - 1) + pre.get(j - 1));
}
}
pre = temp;
list.add(temp);
}
return list;
}

浙公网安备 33010602011771号