-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path118 Pascal's Triangle.js
More file actions
48 lines (43 loc) · 893 Bytes
/
118 Pascal's Triangle.js
File metadata and controls
48 lines (43 loc) · 893 Bytes
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
/**
* Given a non-negative integer numRows, generate the
* first numRows of Pascal's triangle.
* 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
* https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif
*/
/**
* Example:
* Input: 5
* Output:
*[
* [1],
* [1,1],
* [1,2,1],
* [1,3,3,1],
* [1,4,6,4,1]
*]
*/
/**
* @param {number} numRows
* @return {number[][]}
*/
const generate = (numRows) => {
let res = [[1], [1, 1]]
if (numRows === 0) {
return []
} else if (numRows === 1) {
return [[1]]
} else if (numRows === 2) {
return [[1], [1, 1]]
}
for (let i = 1; i <= numRows - 2; i++) {
let add = []
add[0] = 1
for (let j = 1; j < res[i].length; j++) {
add[j] = res[i][j] + res[i][j - 1]
}
add.push(1)
res.push(add)
}
return res
}
console.log(generate(5))