Algo-Sim › Math & Geometry
Pascal's Triangle
Easy · Math & Geometry · step through it in Java, Python and C++ on your own input
Each row comes from the one above: the ends are 1 and every other entry is the sum of the two above it. Entry c of row r is C(r, c).
Problem
Given an integer numRows, return the first numRows rows of Pascal’s triangle, where each number is the sum of the two numbers directly above it.
Constraints
- 1 ≤ numRows ≤ 30
Edge cases to test
- numRows = 1
- Large rows: row 34 overflows a 32-bit int
- numRows = 2
Follow-up questions
- How do you build just one row in O(k) space?
- Update a single array from right to left:
row[j] += row[j − 1](LC 119). - How do you compute C(n, k) directly?
- Multiply
(n − i) / (i + 1)step by step, dividing as you go so values stay exact: O(k).
Solution
Java
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++) {
if (c == 0 || c == r) row.add(1);
else row.add(rows.get(r - 1).get(c - 1) + rows.get(r - 1).get(c));
}
rows.add(row);
}
return rows;
}Python
def generate(num_rows):
rows = []
for r in range(num_rows):
row = []
for c in range(r + 1):
if c == 0 or c == r:
row.append(1)
else:
row.append(rows[r - 1][c - 1] + rows[r - 1][c])
rows.append(row)
return rowsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> rows;
for (int r = 0; r < numRows; r++) {
vector<int> row;
for (int c = 0; c <= r; c++) {
if (c == 0 || c == r) row.push_back(1);
else row.push_back(rows[r - 1][c - 1] + rows[r - 1][c]);
}
rows.push_back(row);
}
return rows;
}
};
More Math & Geometry problems
- Plus One (Easy)
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- nCr mod p (Medium)
- Max Points on a Line (Hard)