【Leetcode】039. 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.

对与一个给定的数组candidates(无重复数)、一个目标值target,求得所有排列唯一的组合数。其中candidates中元素可以出现多次。可以假设candidates是整数


例子

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

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


2019-06-12 深度优先

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def DFS(candidates,target,tmp):
            if target==0:
                res.append(tmp)
                return res
            for i in range(len(candidates)):
                if target>=candidates[i]:
                    DFS(candidates[i:],target-candidates[i],tmp+[candidates[i]])
                else:
                    break
        candidates.sort()
        res = []
        DFS(candidates,target,[])
        #print(res)
        return res
        
S = Solution()
candidates = [2,3,6,7]
target = 7
S.combinationSum(candidates,target)


结果分析

Runtime: 28 ms, faster than 99.91% of Python online submissions for Combination Sum.
Memory Usage: 11.7 MB, less than 81.17% of Python online submissions for Combination Sum.


总结

这题与之前的TwoSum、ThreeSum等实质上是同一种题,但是由于需要找出所有的组合、并且元素的使用次数无限制,导致没办法按照之前的双指针夹逼实现。刚开始拿到这一题,说实在的不会做,基本上是没思路。这里推荐B站博主的动态示意过程LeetCode 39. Combination Sum 中文,看了之后才明白原来是深度优先算法,涉及回溯等操作。清楚整体思路后,直接在网页上编写代码。
自认语言能力不足,描绘起来可能晦涩难懂,暂且不表。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值