forked from dnshi/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPascalsTriangle.js
54 lines (48 loc) · 1.16 KB
/
PascalsTriangle.js
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Source : https://leetcode.com/problems/pascals-triangle
// Author : Dean Shi
// Date : 2017-07-12
/***************************************************************************************
*
* Given numRows, generate the first numRows of Pascal's triangle.
*
* For example, given numRows = 5,
* Return
*
* [
* [1],
* [1,1],
* [1,2,1],
* [1,3,3,1],
* [1,4,6,4,1]
* ]
*
*
***************************************************************************************/
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
const result = []
for (let row, prevRow, i = 0; i < numRows; ++i) {
[row, prevRow] = [[1], result[i - 1] || []]
prevRow.forEach((n, j) => row.push(n + (prevRow[j + 1] || 0)))
result.push(row)
}
return result
};
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
const result = []
for (let row = [], i = 0; i < numRows; ++i) {
row.push(1)
for (let j = i - 1; j > 0; --j) {
row[j] = row[j - 1] + row[j]
}
result.push(row.slice())
}
return result
};