【LeetCode每天一题】Combination Sum II(组合和II)

时间:2022-02-07 13:32:40

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

   这道题的思路和前一道组合数的思路都是类似的,只不过在细节处理上不同。详细思路见代码
解决代码

 class Solution(object):
def combinationSum2(self, nums, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
if len(nums) < 1: # nums为空直接返回
return []
nums.sort() # 对nums进行排序,主要目的是为了较少递归次数。
res =[]
self.get_res(nums, target, [], res) # 递归
return res def get_res(self, nums, target, path, res):
if target == 0: # 结束条件,找到满足的组合将其添加进res列表中
res.append(path)
return
if target < 0: # 没有满足的组合直接返回
return
for i in range(len(nums)): # 从第下标0开始寻找
if i > 0 and nums[i] == nums[i-1]: # 如果当前下小标元素和前一个相等直接跳过,避免产生相同的组合。
continue
if nums[i] > target: # 当前下标直接大于target,后面的元素都不会满足直接返回。
break
self.get_res(nums[i+1:], target-nums[i], path+[nums[i]], res) # 下一次递归时,都将nums大小减一。意味着从下一个开始重新寻找满足条件的组合