118. Pascal's Triangle
Asked at 15Bloomberg64Amazon61Google58Microsoft55Apple51Meta51Bank of America100X94Wipro63Deutsche Bank62Accenture54Zoho52Goldman Sachs48tcs46Infosys30
Problem
Return the first numRows rows of Pascal's triangle, where every number is the sum of the two numbers diagonally above it and each row starts and ends with 1.
Example: numRows = 5 → [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Each row starts and ends with 1; inner values are the sum of the two values above.
Complexity: O(n²).
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
rows = [[1]]
for _ in range(numRows - 1):
prev = rows[-1]
rows.append([1] + [prev[i] + prev[i + 1] for i in range(len(prev) - 1)] + [1])
return rows
assert Solution().generate(5) == [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
assert Solution().generate(1) == [[1]]
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> rows = new ArrayList<>();
for (int r = 0; r < numRows; r++) {
List<Integer> row = new ArrayList<>();
for (int c = 0; c <= r; c++)
row.add(c == 0 || c == r ? 1 : rows.get(r - 1).get(c - 1) + rows.get(r - 1).get(c));
rows.add(row);
}
return rows;
}
}
func generate(numRows int) [][]int {
rows := [][]int{{1}}
for len(rows) < numRows {
prev := rows[len(rows)-1]
row := []int{1}
for i := 0; i+1 < len(prev); i++ {
row = append(row, prev[i]+prev[i+1])
}
rows = append(rows, append(row, 1))
}
return rows
}