https://leetcode.com/problems/pascals-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
- code
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
res.add(Arrays.asList(1));
while (numRows > 1){
numRows--;
List<Integer> last = res.get(res.size() - 1);
List<Integer> new_last = new ArrayList<>();
new_last.add(1);
for (int i = 0; i < last.size() - 1; i++){
new_last.add(last.get(i) + last.get(i+1));
}
new_last.add(1);
res.add(new_last);
}
return res;
}
}
- code
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
def generate_next(lines):
lastline = lines[-1]
next = [1]
for i in range(len(lastline)-1):
next.append(lastline[i]+lastline[i+1])
next.append(1)
lines.append(next)
return lines
if numRows == 1:
return [[1]]
return generate_next(self.generate(numRows-1))