[LeetCode] 40. Combination Sum II_Medium tag: backtracking

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

 

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/10924385.html
0条评论
添加一条新回复