English
119. Pascals Triangle II
Problem Statement
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:
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]
Constraints:
0 <= rowIndex <= 33
Follow up: Could you optimize your algorithm to use only O(rowIndex)
extra space?
Solution:
rs
impl Solution {
pub fn get_row(row_index: i32) -> Vec<i32> {
// create a vector of 1s with length row_index + 1
let mut row = vec![1; (row_index + 1) as usize];
// loop through the vector, starting at 1
for i in 1..row_index {
// loop through the vector, starting at i + 1 and going backwards
for j in (1..=i).rev() {
// add the value at the current index to the value at the previous index
row[j as usize] += row[(j - 1) as usize];
}
}
row
}
}
...