码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode39

时间:2020-05-05 00:55:22      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:bsp   pen   ==   targe   and   不能   数字   sort   一个   

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。 
示例 1:

输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:

输入: candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

【回溯法】

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        res_=[]
        def get_conbine(nums,pre,target):
            if target==0:
                res_.append(nums[::])
            if target<0:
                return;
            nums_=nums[::]
            for i in range(pre,len(candidates)):
                nums.append(candidates[i])
                get_conbine(nums,i,target-candidates[i])
                nums.pop()
            return;
        get_conbine([],0,target)
        return res_

Leetcode39

标签:bsp   pen   ==   targe   and   不能   数字   sort   一个   

原文地址:https://www.cnblogs.com/BetterThanEver_Victor/p/12829051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!