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 d7eac13

Browse files
Update 0377.组合总和IV.md
1 parent ea98e43 commit d7eac13

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

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

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -175,22 +175,36 @@ class Solution {
175175
```
176176

177177
Python:
178-
178+
卡哥版
179179
```python
180180
class Solution:
181-
def combinationSum4(self, nums, target):
181+
def combinationSum4(self, nums: List[int], target: int) -> int:
182182
dp = [0] * (target + 1)
183183
dp[0] = 1
184+
for i in range(1, target + 1): # 遍历背包
185+
for j in range(len(nums)): # 遍历物品
186+
if i - nums[j] >= 0:
187+
dp[i] += dp[i - nums[j]]
188+
return dp[target]
184189

185-
for i in range(1, target+1):
186-
for j in nums:
187-
if i >= j:
188-
dp[i] += dp[i - j]
189-
190-
return dp[-1]
191190
```
191+
优化版
192+
193+
```python
194+
class Solution:
195+
def combinationSum4(self, nums: List[int], target: int) -> int:
196+
dp = [0] * (target + 1) # 创建动态规划数组,用于存储组合总数
197+
dp[0] = 1 # 初始化背包容量为0时的组合总数为1
198+
199+
for i in range(1, target + 1): # 遍历背包容量
200+
for j in nums: # 遍历物品列表
201+
if i >= j: # 当背包容量大于等于当前物品重量时
202+
dp[i] += dp[i - j] # 更新组合总数
192203

204+
return dp[-1] # 返回背包容量为target时的组合总数
193205

206+
207+
```
194208
Go:
195209
```go
196210
func combinationSum4(nums []int, target int) int {

0 commit comments

Comments
(0)

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