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 5c68af9

Browse files
authored
Merge branch 'youngyangyang04:master' into master
2 parents d479e75 + 6b0cc1d commit 5c68af9

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎problems/0377.组合总和IV.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,34 @@ class Solution:
206206

207207

208208
```
209+
二维DP版
210+
```python
211+
class Solution:
212+
def combinationSum4(self, nums: List[int], target: int) -> int:
213+
# dp[][j]和为j的组合的总数
214+
dp = [[0] * (target+1) for _ in nums]
215+
216+
for i in range(len(nums)):
217+
dp[i][0] = 1
218+
219+
# 这里不能初始化dp[0][j]。dp[0][j]的值依赖于dp[-1][j-nums[0]]
220+
221+
for j in range(1, target+1):
222+
for i in range(len(nums)):
223+
224+
if j - nums[i] >= 0:
225+
dp[i][j] = (
226+
# 不放nums[i]
227+
# i = 0 时,dp[-1][j]恰好为0,所以没有特殊处理
228+
dp[i-1][j] +
229+
# 放nums[i]。对于和为j的组合,只有试过全部物品,才能知道有几种组合方式。所以取最后一个物品dp[-1][j-nums[i]]
230+
dp[-1][j-nums[i]]
231+
)
232+
else:
233+
dp[i][j] = dp[i-1][j]
234+
return dp[-1][-1]
235+
```
236+
209237
### Go:
210238

211239
```go

0 commit comments

Comments
(0)

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