forked from TonnyL/Windary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPascalsTriangle.js
90 lines (81 loc) · 1.62 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* 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]
* ]
*
* Accepted.
*/
/**
* @param {number} numRows
* @return {number[][]}
*/
let generate = function (numRows) {
let results = [];
if (numRows === 0) {
return results;
}
if (numRows === 1) {
results.push([1]);
return results;
}
if (numRows === 2) {
results.push([1]);
results.push([1, 1]);
return results;
}
let tmp = generate(numRows - 1);
let list = [];
let last = tmp[tmp.length - 1];
list.push(1);
for (let i = 1; i < last.length; i++) {
list.push(last[i - 1] + last[i]);
}
list.push(1);
tmp.push(list);
return tmp;
};
let lists = [];
if (generate(0).toString() === lists.toString()) {
console.log("pass")
} else {
console.error("failed")
}
lists.push([1]);
if (generate(1).toString() === lists.toString()) {
console.log("pass")
} else {
console.error("failed")
}
lists.push([1, 1]);
if (generate(2).toString() === lists.toString()) {
console.log("pass")
} else {
console.error("failed")
}
lists.push([1, 2, 1]);
if (generate(3).toString() === lists.toString()) {
console.log("pass")
} else {
console.error("failed")
}
lists.push([1, 3, 3, 1]);
if (generate(4).toString() === lists.toString()) {
console.log("pass")
} else {
console.error("failed")
}
lists.push([1, 4, 6, 4, 1]);
if (generate(5).toString() === lists.toString()) {
console.log("pass")
} else {
console.error("failed")
}