[LeetCode] 118. Pascal's Triangle
文章目录
Problem
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]
]
Solution
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if (numRows < 1) return res;
List<Integer> row = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
row.add(0, 1);
for (int j = 1; j < row.size()-1; j++) {
row.set(j, row.get(j)+row.get(j+1));
}
res.add(new ArrayList<>(row));
}
return res;
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论