【LeetCode每天一题】Combination Sum II(组合和II)
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]
]
思路
这道题的思路和前一道组合数的思路都是类似的,只不过在细节处理上不同。详细思路见代码
解决代码
1 class Solution(object):
2 def combinationSum2(self, nums, target):
3 """
4 :type candidates: List[int]
5 :type target: int
6 :rtype: List[List[int]]
7 """
8 if len(nums) < 1: # nums为空直接返回
9 return []
10 nums.sort() # 对nums进行排序,主要目的是为了较少递归次数。
11 res =[]
12 self.get_res(nums, target, [], res) # 递归
13 return res
14
15 def get_res(self, nums, target, path, res):
16 if target == 0: # 结束条件,找到满足的组合将其添加进res列表中
17 res.append(path)
18 return
19 if target < 0: # 没有满足的组合直接返回
20 return
21 for i in range(len(nums)): # 从第下标0开始寻找
22 if i > 0 and nums[i] == nums[i-1]: # 如果当前下小标元素和前一个相等直接跳过,避免产生相同的组合。
23 continue
24 if nums[i] > target: # 当前下标直接大于target,后面的元素都不会满足直接返回。
25 break
26 self.get_res(nums[i+1:], target-nums[i], path+[nums[i]], res) # 下一次递归时,都将nums大小减一。意味着从下一个开始重新寻找满足条件的组合
27