118. 杨辉三角
mengjian-github opened this issue · 1 comments
mengjian-github commented
给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
示例 2:
输入: numRows = 1
输出: [[1]]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
mengjian-github commented
思路比较简单
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
if (numRows === 1) {
return [[1]];
}
const result = [[1], [1, 1]];
for (let i = 2; i < numRows; i++) {
const r = [];
for (let j = 0; j < result[i - 1].length - 1; j++) {
r.push(result[i - 1][j] + result[i - 1][j + 1]);
}
r.unshift(result[i - 1][0]);
r.push(result[i - 1][result[i - 1].length - 1]);
result.push(r);
}
return result;
};