119. Pascal's Triangle II

Easy

Problem Description

Given an integer rowIndex, return the rowIndexth (0-indexed) row of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Examples

Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]

Example 2:
Input: rowIndex = 0
Output: [1]

Example 3:
Input: rowIndex = 1
Output: [1,1]
Jump to Solution: Python Java C++ JavaScript C#

Python Solution


def getRow(rowIndex: int) -> List[int]:
    # Initialize row with 1
    row = [1]
    
    for i in range(rowIndex):
        # Calculate new row in-place from right to left
        for j in range(i, 0, -1):
            row[j] = row[j] + row[j-1]
        # Add new 1 at the end
        row.append(1)
    
    return row

Java Solution


class Solution {
    public List getRow(int rowIndex) {
        List row = new ArrayList<>();
        row.add(1);
        
        for (int i = 0; i < rowIndex; i++) {
            // Calculate new row in-place from right to left
            for (int j = i; j > 0; j--) {
                row.set(j, row.get(j) + row.get(j-1));
            }
            // Add new 1 at the end
            row.add(1);
        }
        
        return row;
    }
}

C++ Solution


class Solution {
public:
    vector getRow(int rowIndex) {
        vector row = {1};
        
        for (int i = 0; i < rowIndex; i++) {
            // Calculate new row in-place from right to left
            for (int j = i; j > 0; j--) {
                row[j] = row[j] + row[j-1];
            }
            // Add new 1 at the end
            row.push_back(1);
        }
        
        return row;
    }
};

JavaScript Solution


/**
 * @param {number} rowIndex
 * @return {number[]}
 */
var getRow = function(rowIndex) {
    const row = [1];
    
    for (let i = 0; i < rowIndex; i++) {
        // Calculate new row in-place from right to left
        for (let j = i; j > 0; j--) {
            row[j] = row[j] + row[j-1];
        }
        // Add new 1 at the end
        row.push(1);
    }
    
    return row;
};

C# Solution


public class Solution {
    public IList GetRow(int rowIndex) {
        IList row = new List { 1 };
        
        for (int i = 0; i < rowIndex; i++) {
            // Calculate new row in-place from right to left
            for (int j = i; j > 0; j--) {
                row[j] = row[j] + row[j-1];
            }
            // Add new 1 at the end
            row.Add(1);
        }
        
        return row;
    }
}

Complexity Analysis

Solution Explanation

This solution uses an optimized in-place approach:

Key points: