ID | Title | Difficulty | |
---|---|---|---|
Loading... |
118. Pascal's Triangle
Easy
LeetCode
Array, Dynamic Programming
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]
]
Code
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
for(int i = 0; i < numRows; i++){
// 在开头插入1
list.add(0, 1);
// 1,2,1 -> 1,1,2,1
// 1,3,3,1
for(int j = 1; j < list.size() - 1; j++){
list.set(j, list.get(j) + list.get(j + 1));
}
res.add(new ArrayList<>(list));
}
return res;
}
}
按 -> 键看下一题!
119. Pascal's Triangle II