王廷瑋|數位醫療|智慧醫療: 119. Pascal's Triangle II WFU

2024年7月6日 星期六

119. Pascal's Triangle II

119. Pascal's Triangle II


給定一個整數 rowIndex,返回帕斯卡三角形中第 rowIndex 行(0 索引)。

在帕斯卡三角形中,每個數字是其正上方的兩個數字之和,如下所示:

範例:

輸入:rowIndex = 3 輸出:[1,3,3,1]


Python


from typing import List

class Solution:
def getRow(self, rowIndex: int) -> List[int]:
# Initialize the first row
row = [1]
# Build each row up to the rowIndex
for i in range(1, rowIndex + 1):
# Use a new row to build the next row based on the current row
newRow = [1] * (i + 1)
for j in range(1, i):
newRow[j] = row[j - 1] + row[j]
row = newRow
return row

16.48MB, 36ms


C++


#include <vector>
using namespace std;

class Solution {
public:
vector<int> getRow(int rowIndex) {
// Initialize the first row
vector<int> row = {1};
// Build each row up to the rowIndex
for (int i = 1; i <= rowIndex; ++i) {
// Use a new row to build the next row based on the current row
vector<int> newRow(i + 1, 1); // Initialize newRow with 1's
for (int j = 1; j < i; ++j) {
newRow[j] = row[j - 1] + row[j];
}
row = newRow;
}
return row;
}
};

7.72MB, 0ms


Javascript

/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
// Initialize the first row
let row = [1];
// Build each row up to the rowIndex
for (let i = 1; i <= rowIndex; ++i) {
// Use a new row to build the next row based on the current row
let newRow = new Array(i + 1).fill(1); // Initialize newRow with 1's
for (let j = 1; j < i; ++j) {
newRow[j] = row[j - 1] + row[j];
}
row = newRow;
}
return row;
};

48.92MB, 34ms