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
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0:
return []
res = []
for i in range(numRows):
t = [1 if j == 0 or j == i else 0 for j in range(i + 1)]
for j in range(1, i):
t[j] = res[i - 1][j - 1] + res[i - 1][j]
res.append(t)
return res
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if (numRows == 0) return res;
for (int i = 0; i < numRows; ++i) {
// 每一行
List<Integer> t = new ArrayList<>();
for (int j = 0; j < i + 1; ++j) {
boolean firstOrLast = j == 0 || j == i;
// 设置每一行首尾元素为1,其它元素为0
t.add(firstOrLast ? 1 : 0);
}
for (int j = 1; j < i; ++j) {
int val = res.get(i - 1).get(j - 1) + res.get(i - 1).get(j);
t.set(j, val);
}
res.add(t);
}
return res;
}
}
const generate = function (numRows) {
let arr = [];
for (let i = 0; i < numRows; i++) {
let row = [];
row[0] = 1;
row[i] = 1;
for (let j = 1; j < row.length - 1; j++) {
row[j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr.push(row);
}
return arr;
};