Post

118 Pascals Triangle

118 Pascals Triangle

Pascal’s Triangle image

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:

image

 

Example 1:

1
2
3
**Input:** numRows = 5
**Output:** [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

1
2
3
**Input:** numRows = 1
**Output:** [[1]]

 

Constraints:

1
1 <= numRows <= 30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

impl Solution {
    pub fn generate(num_rows: i32) -> Vec<Vec<i32>> {
        let mut res : Vec<Vec<i32>> = Vec::new();
        let mut temp : Vec<i32> = Vec::new();
        temp.push(1);
        res.push(temp.clone());
        for i in 1..num_rows {
            let mut f = 0;
            let mut r = 1;
            let mut temp_to_add = Vec::new();
            temp_to_add.push(1);
            while (r < temp.len()) {
                temp_to_add.push(temp[f] + temp[r]);
                f += 1;
                r += 1;
            }
            temp_to_add.push(1);
            res.push(temp_to_add.clone());
            temp = temp_to_add;
        }
        res
    }
}



This post is licensed under CC BY 4.0 by the author.