Skip to main content
Back to problems
#118
Easy Algorithms

Pascals triangle

Array Dynamic Programming
78.7% acceptance
Jan 12, 2026
14856
564
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn generate(num_rows: i32) -> Vec<Vec<i32>> {
    let mut result: Vec<Vec<i32>> = Vec::with_capacity(num_rows as usize);
    
    for i in 0..num_rows as usize {
      let mut row = Vec::with_capacity(i + 1);
      row.push(1);
      
      if i > 0 {
        let prev = &result[i - 1];
        for j in 0..prev.len() - 1 {
          row.push(prev[j] + prev[j + 1]);
        }
        row.push(1);
      }
      
      result.push(row);
    }
    
    result
  }
}