一、原题目
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
二、题目大意
给定一个没有重复元素的列表和一个整数k
要求:求列表的子集之和为k,选取可重复,组合不重复,返回组合个数。
三、思路分析
别人的思路:
利用动态规划来解决。
本人的思路:
初看这道题目,有了前面几个版本的基础,做这个题目感觉简单,但是结果出乎意料。(详细见本人这类题目其他博客文章)
四、具体代码
作者的代码:
class Solution(object):
def combinationSum4(self, nums, target):
nums.sort()
dp=[0]*(target+1)#共享id
dp[0]=1 # if num == target
for i in xrange(1,target+1):
for num in nums:
if num>i:
break
dp[i]+=dp[i-num]
return dp[target]
本人的代码:
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
nums.sort()
res=[]
self.dfs(nums,target,[],res)
return len(res)
def dfs(self,nums,target,path,res):
if target<0:
return
if target==0:
res.append(path)
for i in range(len(nums)):
self.dfs(nums,target-nums[i],path+[nums[i]],res)
五、两者差别
本人代码超时,作者代码测试通过。
本人用的是深度搜索,而作者用的动态规划思路。
六、知识点总结
动态规划:https://blog.csdn.net/u013309870/article/details/75193592(参考博客链接,很详细,强烈推荐)
七、.来源
题目连接:https://leetcode.com/problems/combination-sum-iv/
作者原文解答:https://leetcode.com/problems/combination-sum-iv/discuss/85145/Python-DP-and-DFS-Solution
座右铭:站在别人的思想上,看见自己的不足,传播错误的经验,愿君不重蹈覆辙。
由于受限于本人经验,难免不足,如有建议,欢迎留言交流。
说明:作者代码能通过测试,本人亲测。如果喜欢,请点赞,您的鼓励是本人前进的最好动力。
---------------------
作者:路漫漫,远修兮
来源:CSDN
原文:https://blog.csdn.net/qq_41827968/article/details/88756403
版权声明:本文为博主原创文章,转载请附上博文链接!