File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Problem: https://leetcode.com/problems/pascals-triangle/
2
+ // Doc: https://leetcode.com/problems/pascals-triangle/solutions/5471283/generating-pascal-s-triangle-efficiently/
3
+ const generate = ( numRows : number ) : number [ ] [ ] => {
4
+ const result = [ [ 1 ] ] ;
5
+ if ( numRows === 1 ) return result ;
6
+
7
+ for ( let i = 1 ; i < numRows ; i ++ ) {
8
+ const prev = result [ i - 1 ] ;
9
+ const row = [ 1 ] ;
10
+ for ( let j = 0 ; j < prev . length - 1 ; j ++ ) {
11
+ const l = prev [ j ] ;
12
+ const r = prev [ j + 1 ] ;
13
+ row . push ( l + r ) ;
14
+ }
15
+ row . push ( 1 ) ;
16
+ result . push ( row ) ;
17
+ }
18
+
19
+ return result ;
20
+ } ;
21
+
22
+ describe ( "Pascal's Triangle" , ( ) => {
23
+ it ( 'should return the pascal triangle' , ( ) => {
24
+ expect ( generate ( 5 ) ) . toEqual ( [
25
+ [ 1 ] ,
26
+ [ 1 , 1 ] ,
27
+ [ 1 , 2 , 1 ] ,
28
+ [ 1 , 3 , 3 , 1 ] ,
29
+ [ 1 , 4 , 6 , 4 , 1 ] ,
30
+ ] ) ;
31
+ expect ( generate ( 1 ) ) . toEqual ( [ [ 1 ] ] ) ;
32
+ } ) ;
33
+ } ) ;
You can’t perform that action at this time.
0 commit comments