Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4b7e493

Browse files
committed
Update 0118. 杨辉三角.md
1 parent 5e64245 commit 4b7e493

File tree

1 file changed

+61
-11
lines changed

1 file changed

+61
-11
lines changed

‎Solutions/0118. 杨辉三角.md‎

Lines changed: 61 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,73 @@
55

66
## 题目大意
77

8-
给定一个整数 n,生成前 n 行的杨辉三角
8+
**描述**:给定一个整数 `n`
99

10-
例如 n = 5:
10+
**要求**:生成前 `n` 行的杨辉三角。
1111

12+
**说明**:
13+
14+
- 1ドル \le numRows \le 30$。
15+
16+
**示例**:
17+
18+
```Python
19+
输入 numRows = 5
20+
输出 [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
1221
```
13-
[
14-
[1],
15-
[1,1],
16-
[1,2,1],
17-
[1,3,3,1],
18-
[1,4,6,4,1]
19-
]
20-
```
22+
23+
![](https://pic.leetcode-cn.com/1626927345-DZmfxB-PascalTriangleAnimated2.gif)
2124

2225
## 解题思路
2326

24-
两重循环遍历。先遍历 n 行,再对每一行每个位置上的元素进行赋值计算。每一行两侧元素赋值为 1,中间元素为上一行两个元素相加。
27+
### 思路 1:动态规划
28+
29+
###### 1. 划分阶段
30+
31+
按照行数进行阶段划分。
32+
33+
###### 2. 定义状态
34+
35+
定义状态 `dp[i][j]` 为:杨辉三角第 `i` 行、第 `j` 列位置上的值。
36+
37+
###### 3. 状态转移方程
38+
39+
根据观察,很容易得出状态转移方程为:`dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]`,此时 `i > 0,j > 0`
40+
41+
###### 4. 初始条件
42+
43+
- 每一行第一列都为 `1`,即 `dp[i][0] = 1`
44+
- 每一行最后一列都为 `1`,即 `dp[i][i] = 1`
45+
46+
###### 5. 最终结果
47+
48+
根据题意和状态定义,我们将每行结果存入答案数组中,将其返回。
49+
50+
### 思路 1:动态规划代码
51+
52+
```Python
53+
class Solution:
54+
def generate(self, numRows: int) -> List[List[int]]:
55+
dp = [[0] * i for i in range(1, numRows + 1)]
56+
57+
for i in range(numRows):
58+
dp[i][0] = 1
59+
dp[i][i] = 1
60+
61+
res = []
62+
for i in range(numRows):
63+
for j in range(i):
64+
if i != 0 and j != 0:
65+
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
66+
res.append(dp[i])
67+
68+
return res
69+
```
70+
71+
### 思路 1:复杂度分析
72+
73+
- **时间复杂度**:$O(n^2)$。初始条件赋值的时间复杂度为 $O(n),ドル两重循环遍历的时间复杂度为 $O(n^2),ドル所以总的时间复杂度为 $O(n^2)$。
74+
- **空间复杂度**:$O(n^2)$。用到了二维数组保存状态,所以总体空间复杂度为 $O(n^2)$。
2575

2676
## 代码
2777

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /