Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
計算巴斯卡三角形
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
這題的重點在於如何抓到上一個陣列的值,算出現有陣列的值。
var generate = function (numRows) {
let a = [];
let a1 = [1];
let a3 = [];
for (let i = 0; i < numRows; i++) {
a = a1.slice(0);
if (i !== 0) {
a1 = [];
}
a3.push(a);
for (let j = 0; j < i + 1; j++) {
if (j === 0) {
a1.push(1);
} else {
a1.push(a[j - 1] + a[j]);
}
if (j === i && i !== 0) {
a1.push(1);
}
}
}
return a3;
};