File tree 1 file changed +12
-26
lines changed
1 file changed +12
-26
lines changed Original file line number Diff line number Diff line change 3
3
// the time complexity will basically be the number of elements in pascale tringle. roughly height of tringle * number of honeycomb in each row.
4
4
// O(n^2);
5
5
6
- var generate = function ( num ) {
7
-
8
- const outerArray = [ ] ;
9
- // adding first two rows of pascals triangle
10
- if ( num >= 2 ) {
11
- outerArray . push ( [ 1 ] ) ;
12
- outerArray . push ( [ 1 , 1 ] ) ;
13
- } else {
14
- outerArray . push ( [ 1 ] ) ;
15
- }
16
-
17
- // will only run if we had number greater than 2
18
- if ( num > 2 ) {
19
- for ( let i = 2 ; i < num ; i ++ ) {
20
- let subArray = [ ] ;
21
- subArray . push ( 1 ) ;
22
- for ( let j = 0 ; j < outerArray [ i - 1 ] . length - 1 ; j ++ ) {
23
- subArray . push ( outerArray [ i - 1 ] [ j ] + outerArray [ i - 1 ] [ j + 1 ] ) ;
24
- }
25
- subArray . push ( 1 ) ;
26
- outerArray . push ( subArray ) ;
27
- }
28
- }
29
-
30
- return outerArray ;
31
- } ;
6
+ var generate = function ( numRows ) {
7
+ const res = [ [ 1 ] ] ;
8
+
9
+ for ( let i = 1 ; i < numRows ; i ++ ) {
10
+ res [ i ] = [ ] ;
11
+ for ( let k = 0 ; k < i + 1 ; k ++ ) {
12
+ res [ i ] [ k ] = ( res [ i - 1 ] [ k ] || 0 ) + ( res [ i - 1 ] [ k - 1 ] || 0 ) ;
13
+ }
14
+ }
15
+
16
+ return res ;
17
+ } ;
You can’t perform that action at this time.
0 commit comments