| title | 118. 杨辉三角 | |||||||
|---|---|---|---|---|---|---|---|---|
| description | LeetCode 118. 杨辉三角题解,Pascal's Triangle,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。 | |||||||
| keywords |
|
🟢 Easy 🔖 数组 动态规划 🔗 力扣 LeetCode
Given an integer numRows, return the first numRows of Pascal 's
triangle.
In Pascal 's triangle, each number is the sum of the two numbers directly above it as shown:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
1 <= numRows <= 30
给定一个非负整数 *numRows,*生成「杨辉三角」的前 *numRows *行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
示例 1:
输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
示例 2:
输入: numRows = 1
输出: [[1]]
提示:
1 <= numRows <= 30
- 构建基础结构:初始化一个大小为
n的数组,来存储每一行的元素。 - 逐行生成:第
i行的第j个元素为上一行的第j-1和第j个元素之和,除了第一个和最后一个元素是1。 - 返回结果:构造完所有的行后,将完整的数组返回。
- 时间复杂度:
O(n^2),其中n是行数。因为需要遍历每一行并更新每个元素的值。 - 空间复杂度:
O(n^2),用于存储整个 Pascal 三角形。
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function (numRows) {
let res = [];
// 生成每一行
for (let i = 0; i < numRows; i++) {
// 每一行的长度为i+1,并初始化为1
let row = new Array(i + 1).fill(1);
// 更新除第一个和最后一个元素之外的元素
for (let j = 1; j < i; j++) {
row[j] = res[i - 1][j - 1] + res[i - 1][j];
}
// 将当前行加入结果
res.push(row);
}
return res;
};| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 119 | 杨辉三角 II | [✓] | 数组 动态规划 |
🟢 | 🀄️ 🔗 |