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 978f347

Browse files
🐱(array): 119. 杨辉三角 II
补充递归
1 parent 2581b7f commit 978f347

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎docs/data-structure/array/README.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1087,6 +1087,27 @@ class Solution(object):
10871087
return res
10881088
```
10891089

1090+
优化:
1091+
1092+
```go
1093+
func generate(numRows int) [][]int {
1094+
var res [][]int = make([][]int, numRows)
1095+
1096+
for i := 0; i < numRows; i++ {
1097+
res[i] = make([]int, i + 1)
1098+
for j := 0; j < i + 1; j++ {
1099+
if j == 0 || j == i {
1100+
res[i][j] = 1
1101+
} else {
1102+
res[i][j] = res[i - 1][j - 1] + res[i - 1][j]
1103+
}
1104+
}
1105+
}
1106+
1107+
return res
1108+
}
1109+
```
1110+
10901111

10911112
## 119. 杨辉三角 II
10921113

@@ -1124,6 +1145,32 @@ class Solution(object):
11241145
return cur
11251146
```
11261147

1148+
### 解二:递归
1149+
1150+
```python
1151+
class Solution:
1152+
def generate(self, numRows: int) -> List[List[int]]:
1153+
ans = []
1154+
# 递归:输入上一行,返回下一行
1155+
def helper(pre):
1156+
length = len(pre)
1157+
if length == numRows:
1158+
return
1159+
if length == 0:
1160+
nxt = [1]
1161+
elif length == 1:
1162+
nxt = [1, 1]
1163+
else:
1164+
nxt = [1]
1165+
for i in range(length - 1):
1166+
nxt.append(pre[i] + pre[i + 1])
1167+
nxt.append(1)
1168+
ans.append(nxt)
1169+
helper(nxt)
1170+
1171+
helper([])
1172+
return ans
1173+
```
11271174

11281175
## 121. 买卖股票的最佳时机
11291176

0 commit comments

Comments
(0)

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