File tree Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -116,3 +116,4 @@ mod n0112_path_sum;
116116mod n0113_path_sum_ii;
117117mod n0114_flatten_binary_tree_to_linked_list;
118118mod n0115_distinct_subsequences;
119+ mod n0118_pascals_triangle;
Original file line number Diff line number Diff line change 1+ /**
2+ * [118] Pascal's Triangle
3+ *
4+ * Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
5+ *
6+ * <img alt="" src="https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif" style="height:240px; width:260px" /><br />
7+ * <small>In Pascal's triangle, each number is the sum of the two numbers directly above it.</small>
8+ *
9+ * Example:
10+ *
11+ *
12+ * Input: 5
13+ * Output:
14+ * [
15+ * [1],
16+ * [1,1],
17+ * [1,2,1],
18+ * [1,3,3,1],
19+ * [1,4,6,4,1]
20+ * ]
21+ *
22+ *
23+ */
24+ pub struct Solution { }
25+
26+ // submission codes start here
27+
28+ impl Solution {
29+ pub fn generate ( num_rows : i32 ) -> Vec < Vec < i32 > > {
30+ let mut res = Vec :: new ( ) ;
31+ if num_rows < 1 { return res }
32+ let mut curr = vec ! [ 1 ] ;
33+ for _ in 0 ..num_rows {
34+ let mut next = vec ! [ 1 ; curr. len( ) +1 ] ;
35+ for i in 1 ..curr. len ( ) {
36+ next[ i] = curr[ i-1 ] + curr[ i] ;
37+ }
38+ res. push ( curr) ;
39+ curr = next;
40+ }
41+ res
42+ }
43+ }
44+
45+ // submission codes end
46+
47+ #[ cfg( test) ]
48+ mod tests {
49+ use super :: * ;
50+
51+ #[ test]
52+ fn test_118 ( ) {
53+ assert_eq ! ( Solution :: generate( 1 ) , vec![ vec![ 1 ] ] ) ;
54+ assert_eq ! (
55+ Solution :: generate( 5 ) ,
56+ vec![
57+ vec![ 1 ] ,
58+ vec![ 1 , 1 ] ,
59+ vec![ 1 , 2 , 1 ] ,
60+ vec![ 1 , 3 , 3 , 1 ] ,
61+ vec![ 1 , 4 , 6 , 4 , 1 ]
62+ ] ) ;
63+ }
64+ }
You can’t perform that action at this time.
0 commit comments