Skip to content

Commit b695fdf

Browse files
author
aestheticw3
authoredSep 7, 2023
Update 0118-pascals-triangle.js
1 parent db7509f commit b695fdf

File tree

1 file changed

+12
-26
lines changed

1 file changed

+12
-26
lines changed
 

‎javascript/0118-pascals-triangle.js

+12-26
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,15 @@
33
// the time complexity will basically be the number of elements in pascale tringle. roughly height of tringle * number of honeycomb in each row.
44
// O(n^2);
55

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+
};

0 commit comments

Comments
 (0)
Please sign in to comment.