HomeLeetcodePascal's Triangle II (Task 119 Array) - Solutions

Pascal’s Triangle II (Task 119 Array) – Solutions

Description:

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

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

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]

Solution in Python:

To solve this problem, we need to generate the rowIndex-th row of Pascal’s Triangle. Each element in the triangle is the sum of the two elements directly above it in the previous row.

Here’s a step-by-step explanation of the approach we’ll use:

  1. Initialization: Start with the first row, which is [1].
  2. Iteration: For each subsequent row up to rowIndex, generate the next row based on the current row.
  3. Row Generation: The new row can be generated by adding pairs of adjacent elements from the current row. For instance, if the current row is [1, 3, 3, 1], the next row starts and ends with 1, and the middle elements are sums of adjacent elements from the current row (i.e., 1+3, 3+3, 3+1).
  4. Edge Case: If rowIndex is 0, return [1] immediately.
Python
class Solution:
    def getRow(self, rowIndex: int) -> list[int]:
        # Initialize the first row of Pascal's Triangle
        row = [1]
        
        # Generate rows until we reach the desired rowIndex
        for _ in range(rowIndex):
            # Create the next row
            new_row = [1]  # Start with 1
            for j in range(1, len(row)):
                # Each new element is the sum of the two elements above it
                new_row.append(row[j - 1] + row[j])
            new_row.append(1)  # End with 1
            row = new_row  # Move to the next row
        
        return row

# Example usage:
# sol = Solution()
# print(sol.getRow(3))  # Output: [1, 3, 3, 1]
# print(sol.getRow(0))  # Output: [1]
# print(sol.getRow(1))  # Output: [1, 1]

Explanation of the Code:

  1. Initialization:
    • Start with the first row, [1].
  2. Loop to Generate Rows:
    • Use a loop to generate each row from the previous row.
    • For each new row, start with [1].
    • Use another loop to compute the inner elements by summing pairs of adjacent elements from the previous row.
    • Append 1 at the end of the new row.
    • Update the current row to the new row.
  3. Return the Desired Row:
    • After completing the iterations, the row variable will contain the rowIndex-th row of Pascal’s Triangle.

This approach ensures that we efficiently build the row we need without constructing the entire Pascal’s Triangle up to that row.

Solution in Javascript:

JavaScript
/**
 * @param {number} rowIndex
 * @return {number[]}
 */
var getRow = function(rowIndex) {
    // Initialize the first row of Pascal's Triangle
    let row = [1];
    
    // Generate rows until we reach the desired rowIndex
    for (let i = 0; i < rowIndex; i++) {
        // Create the next row
        let newRow = [1];  // Start with 1
        for (let j = 1; j < row.length; j++) {
            // Each new element is the sum of the two elements above it
            newRow.push(row[j - 1] + row[j]);
        }
        newRow.push(1);  // End with 1
        row = newRow;  // Move to the next row
    }
    
    return row;
};

// Example usage:
console.log(getRow(3));  // Output: [1, 3, 3, 1]
console.log(getRow(0));  // Output: [1]
console.log(getRow(1));  // Output: [1, 1]

Solution in Java:

Java
import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> getRow(int rowIndex) {
        // Initialize the first row of Pascal's Triangle
        List<Integer> row = new ArrayList<>();
        row.add(1);
        
        // Generate rows until we reach the desired rowIndex
        for (int i = 0; i < rowIndex; i++) {
            // Create the next row
            List<Integer> newRow = new ArrayList<>();
            newRow.add(1);  // Start with 1
            
            // Each new element is the sum of the two elements above it
            for (int j = 1; j < row.size(); j++) {
                newRow.add(row.get(j - 1) + row.get(j));
            }
            
            newRow.add(1);  // End with 1
            row = newRow;  // Move to the next row
        }
        
        return row;
    }

    // Example usage
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.getRow(3));  // Output: [1, 3, 3, 1]
        System.out.println(sol.getRow(0));  // Output: [1]
        System.out.println(sol.getRow(1));  // Output: [1, 1]
    }
}

Solution in C#:

C#
using System;
using System.Collections.Generic;

public class Solution {
    public IList<int> GetRow(int rowIndex) {
        // Initialize the first row of Pascal's Triangle
        List<int> row = new List<int> { 1 };
        
        // Generate rows until we reach the desired rowIndex
        for (int i = 0; i < rowIndex; i++) {
            // Create the next row
            List<int> newRow = new List<int> { 1 };  // Start with 1
            
            // Each new element is the sum of the two elements above it
            for (int j = 1; j < row.Count; j++) {
                newRow.Add(row[j - 1] + row[j]);
            }
            
            newRow.Add(1);  // End with 1
            row = newRow;  // Move to the next row
        }
        
        return row;
    }


}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular