Pascal's Triangle — Row-by-Row DP Generation [Easy]

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem Statement

Input: numRows = 5[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]].

Key Insight: Row i has i+1 elements. row[0] = row[i] = 1. For interior positions j: row[j] = prev_row[j-1] + prev_row[j].

C Solution

// C — allocate jagged array
#include <stdlib.h>
int** generate(int numRows, int* retRowSz, int** colSizes) {
    int** tri = malloc(numRows * sizeof(int*));
    *colSizes = malloc(numRows * sizeof(int));
    *retRowSz = numRows;
    for (int i = 0; i < numRows; i++) {
        tri[i] = malloc((i+1) * sizeof(int));
        (*colSizes)[i] = i+1;
        tri[i][0] = tri[i][i] = 1;
        for (int j = 1; j < i; j++)
            tri[i][j] = tri[i-1][j-1] + tri[i-1][j];
    }
    return tri;
}

C++ Solution

#include <vector>
using namespace std;
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> tri;
        for (int i = 0; i < numRows; i++) {
            vector<int> row(i+1, 1);
            for (int j = 1; j < i; j++)
                row[j] = tri[i-1][j-1] + tri[i-1][j];
            tri.push_back(row);
        }
        return tri;
    }
};

Java Solution

import java.util.*;
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> tri = new ArrayList<>();
        for (int i = 0; i < numRows; i++) {
            Integer[] row = new Integer[i+1];
            Arrays.fill(row, 1);
            for (int j = 1; j < i; j++)
                row[j] = tri.get(i-1).get(j-1) + tri.get(i-1).get(j);
            tri.add(Arrays.asList(row));
        }
        return tri;
    }
}

JavaScript Solution

function generate(numRows) {
    const tri = [];
    for (let i = 0; i < numRows; i++) {
        const row = new Array(i+1).fill(1);
        for (let j = 1; j < i; j++)
            row[j] = tri[i-1][j-1] + tri[i-1][j];
        tri.push(row);
    }
    return tri;
}

Python Solution

def generate(numRows):
    triangle = []
    for i in range(numRows):
        row = [1] * (i + 1)
        for j in range(1, i):
            row[j] = triangle[i-1][j-1] + triangle[i-1][j]
        triangle.append(row)
    return triangle

Complexity Analysis

| O(numRows²) time | O(numRows²) space |

Follow-up: Pascal's Triangle II — return only the kth row using a single 1D array (update from right to left).

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro