118. Pascal's Triangle
Description of the Problem
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:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
1 <= numRows <= 30
Solution
Explanation
In case you do not know Pascal Identity \( C^{n}_{r} = C^{n-1} _{r-1} + C^{n-1} _{r} \)
Code (Rust)
impl Solution {
pub fn generate(num_rows: i32) -> Vec<Vec<i32>> {
let mut result : Vec<Vec<i32>> = Vec::new();
for n in 0..num_rows {
let mut row : Vec<i32> = Vec::new();
for i in 0..=n {
row.push(
if i == n || i == 0 {
1
}
else{
result[(n - 1) as usize][(i - 1) as usize]
+ result[(n - 1) as usize][i as usize]
}
)
}
result.push(row);
}
return result;
}
}
Complexity
- n is the number of rows
Time complexity:
- \( T(n) = O(n^2) \)
- \(1+2+3...+n+(n+1) = \frac{(n+1)(n+2)}{2}\)
Auxiliary Space:
- \( S(n) = O(n^2) \)