LeetCode Medium: 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.

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]
]

题目大意:意思说 给一组正数C,然后 给你一个目标数T, 让你从那组C中找到加在一起等于T的那些组合。 
比如 给定target=7,然后 从[2,3,6,7]中可以找到[2,2,3]和[7]两组组合。 

二、思路

用深度优先(DFS),看到题目后,有想到使用DFS思想,但是具体不太会实现,因为仅仅毕竟不太熟悉,看了别人的博客(后附),觉得写得很好,所以搬过来,供大家参考。

主要思想是:

Target =T,然后从数组中找一个数n,然后在 剩下的部分target 变成了 T-n,以此类推。函数到哪返回呢,如果目标数T=0,则找的成功,返回,如果目标数T小于C中最小的数,言外之意就是我们找到不这样的组合了,寻找失败,返回。 需要注意的是,答案要求没有重复的,如果只是这么写会变成[2,3,2],[2,2,3],[3,2,2],因此要记下 上一个数,我是从小往大找的,也就是说,如果我已经找完n=2的情况,再去找n=3的时候,3就不应该往回再选n=2了,只能往后走,不然就会重复。

三、代码

#coding:utf-8
class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.resList = []
        candidates = sorted(candidates)
        self.dfs(candidates,[],target,0)
        print(self.resList)
        return self.resList
    def dfs(self,candidates,sublist,target,last):
        if target == 0:
            self.resList.append(sublist[:])
        if target < candidates[0]:
            return
        for n in candidates:
            if n > target:
                return
            if n < last:
                continue
            sublist.append(n)
            self.dfs(candidates,sublist,target-n,n)
            sublist.pop()

    # def onlyonecandidate(self,candidate,target):
    #     solutionset=[]
    #     solutionsets = []
    #     if target % candidate == 0:
    #         repeat = target // candidate
    #         solutionset = [repeat for i in range(repeat)]  #在solutionset中将repeat复制repeat次
    #         print(solutionset)
    #     solutionsets.append(solutionset)
    #     print(solutionsets)
    #     return solutionsets

if __name__ == '__main__':
    # repeat = [1,4,6]
    # for i in repeat:
    #     print(i)
    candidates = [2,4,3,1]
    target = 5
    ss = Solution()
    ss.combinationSum(candidates,target)

 参考博客:https://blog.csdn.net/zl87758539/article/details/51693179  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8985750.html