LeetCode_40. Combination Sum II_路漫漫远修兮

一、原题目

 

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

Each number in candidates may only be used once in the combination.

Note:

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

 
二、题目大意

给定一个列表和整数,求列表的子集。其中,子集中所有元素的和等于给定的整数。
并且列表中元素在子集列表中只能出现一次。


三、思路分析

本人的思路:

这道题目与第一个版本的区别就是:
第一个版本,列表中无重复元素,但是取元素的时候,每个元素的选取次数不限
这个版本,列表中有重复元素,但是取元素的时候,在一个组合中每个元素只能取一次

也就是说,在一次遍历过程中,每个值只能取一次,这个问题的关键就是如何
区分列表中的重复元素。保证取一次,可以通过遍历顺序来控制。

 

四、具体代码

本人的代码:

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()#排序
        res=[]
        self.dfs(candidates,target,[],res)
        re=[]
        for i in res:#去除重复列表子集
            if i not in re:
                re.append(i)
        return re       
    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[i+1:],target-nums[i],path+[nums[i]],res)

 

 

五、来源


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


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

 

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

 

说明:这个类型题目的代码,本人都是在第一个别人写的代码上根据具体题目改编而来,所以第一个版本值得看看。


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值