LeetCode_39. Combination Sum_路漫漫远修兮

一、原题目

 

Given a set of candidate numbers (candidates(without duplicates)and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 
二、题目大意

给定一个无重复元素的列表n和一个目标整数k,求列表的子集,子集列表满足里面的
元素之和等于目标整数。列表n中的元素在子集列表中可以重复出现无数次。


三、思路分析

 

别人的思路:

先对列表进行排序,在利用深度搜索算法求得结果。

 

四、具体代码

 

作者的代码:

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        res=[]
        candidates.sort()#排序
        self.dfs(candidates,target,0,[],res)
        return res
    def dfs(self,nums,target,index,path,res):
        if target<0:#这里包含两种情况,一是没有遍历到列表末尾(在中间的时候就不符合要求),
             #二是遍历到列表末尾 结果其实与这两种情况关系不大,只有等于的时候才加入,
             #这里给自己的感觉就是,既然不符合要求,为什么不进行处理了
             #后来仔细想了下,处理在path中,当回退时,path的路径也变了
            return 
        if target==0:#选出符合要求的组合
            res.append(path)
            return
        for i in range(index,len(nums)):
            self.dfs(nums,target-nums[i],i,path+[nums[i]],res)
            #选取当前值,找下一个邻接点
           #可以把递归看成多个for循环的作用,每一个子列表都构成一个for循环
           #通过不断的筛选,来得到结果。

#以上注释为本人写,代码别人。

 

五、知识点总结

深度优先搜索算法:

大概思路,深度优先搜索算法就是从一个点开始,不断找邻接点,当没有邻接点时,回退,重复上面步骤,遍历完所有
情况。

 

六、.来源


题目连接:https://leetcode.com/problems/combination-sum/

作者原文解答:https://leetcode.com/problems/combination-sum/discuss/16510/Python-dfs-solution.

 
座右铭:站在别人的思想上,看见自己的不足,传播错误的经验,愿君不重蹈覆辙。

 

由于受限于本人经验,难免不足,如有建议,欢迎留言交流。

 

说明:作者代码能通过测试,本人亲测。如果喜欢,请点赞,您的鼓励是本人前进的最好动力。


--------------------- 
作者:路漫漫,远修兮 
来源:CSDN 
原文:https://blog.csdn.net/qq_41827968/article/details/88756403 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值