首页 > 其他 > 详细

[LeetCode] 40. Combination Sum II_Medium tag: backtracking

时间:2019-05-25 23:48:12      阅读:184      评论:0      收藏:0      [点我收藏+]

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.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

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

这个题目实际上就是[LeetCode] 90.Subsets II tag: backtracking只不过要找到符合条件的subset,再append进入ans中。

Note: 因为都是positive number,如果nums[i] > target: continue

Code

class Solution:    
    def combinationSum(self, nums, target):
        ans = []
        nums.sort() # because has duplicates
        self.search(ans, nums, [], 0, target)
        return ans
    
    def search(self, ans, nums, temp, pos, target):
        if target == 0:
            ans.append(temp)
        for i in range(pos, len(nums)):
            if nums[i] > target or (i > pos and nums[i] == nums[i - 1]):
                continue
            self.search(ans, nums, temp + [nums[i]], i + 1, target - nums[i])

 

[LeetCode] 40. Combination Sum II_Medium tag: backtracking

原文:https://www.cnblogs.com/Johnsonxiong/p/10924385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!