118. Pascal's Triangle
給定一個整數 numRows,返回帕斯卡三角形的前 numRows 行。
在帕斯卡三角形中,每個數字是其正上方的兩個數字之和,如下所示:
範例:
輸入:numRows = 5 輸出:[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Python
from typing import List
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0:
return []
triangle = [[1]]
for i in range(1, numRows):
row = [1]
for j in range(1, i):
row.append(triangle[i-1][j-1] + triangle[i-1][j])
row.append(1)
triangle.append(row)
return triangle
16.47MB, 34ms
C++
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> triangle;
if (numRows == 0) {
return triangle;
}
// Initialize the first row of the triangle
triangle.push_back({1});
for (int i = 1; i < numRows; ++i) {
vector<int> row;
row.push_back(1); // First element is always 1
// Compute the intermediate values
for (int j = 1; j < i; ++j) {
row.push_back(triangle[i-1][j-1] + triangle[i-1][j]);
}
row.push_back(1); // Last element is always 1
triangle.push_back(row);
}
return triangle;
}
};
7.93MB, 0ms
Javascript
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
const triangle = [];
if (numRows === 0) {
return triangle;
}
// Initialize the first row of the triangle
triangle.push([1]);
for (let i = 1; i < numRows; ++i) {
const row = [];
const prevRow = triangle[i - 1];
row.push(1); // First element is always 1
// Compute the intermediate values
for (let j = 1; j < i; ++j) {
row.push(prevRow[j - 1] + prevRow[j]);
}
row.push(1); // Last element is always 1
triangle.push(row);
}
return triangle;
};
49.74MB, 61ms