Pascal’s Triangle (E)
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
题意
生成前n行帕斯卡(杨辉)三角形。
思路
直接模拟操作生成每一行。
代码实现
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new ArrayList<>();
if (numRows == 0) {
return ans;
}
ans.add(new ArrayList<>());
ans.get(0).add(1);
for (int i = 1; i < numRows; i++) {
ans.add(new ArrayList<>(ans.get(i - 1)));
List<Integer> curRow = ans.get(i);
for (int j = i; j >= 1; j--) {
if (j == i) {
curRow.add(1);
} else {
curRow.set(j, curRow.get(j) + curRow.get(j - 1));
}
}
}
return ans;
}
}