LeetCode-39. Combination Sum

0.原题

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.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

 

1.代码

class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.result = []
        self.one_result = []
        self.candidates = candidates
        self.fun(target)
        return self.result

    def fun(self,target):
        if target < 0:
            return -1
        elif target == 0:
            r = self.one_result.copy()
            r.sort()
            if r not in self.result:
                self.result.append(r)
            return 0
        else:
            for candidate in self.candidates:
                self.one_result.append(candidate)
                new_target = target-candidate
                self.fun(new_target)
                self.one_result.pop()

解题关键点:

本题思路很简单:本题利用递归+遍历,不断地尝试选取candidates中的值,直到满足条件即可。每层递归,另target = target - candidate,如果target == 0 ,即表示找到了一组解。

难点在于,如何判重?比如[2,3,3]、[3,2,3]、[3,3,2]都是一组解。

将符合条件的解(列表)进行排序操作,那么[2,3,3]、[3,2,3]、[3,3,2]排序之后都是[2,3,3],这样就解决了判重问题。

 

代码中需要注意的地方:

在这段代码中,我们执行了r = self.one_result.copy()操作,因为list是mutable object,不拷贝直接使用,则传递是self.one_result的指针,那么result中保存的只有self.one_result的最终结果。具体原因详见:

https://blog.csdn.net/qq_17753903/article/details/82886625

另外,对one_result的排序也必须在副本上进行,即r.sort()。因为,递归返回后,要执行one_result.pop()操作,如果对one_result先进行了排序,那么弹出的就不一定是最后一个元素了,从而导致程序错误。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值