难度: Medium
原题连接
内容描述
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 - 时间复杂度: O(2^n)- 空间复杂度: O(2^n)******
Combination Sum 已经AC,做了minor change.
- 递归取了当前这个数的时候
idx
也要从idx+1
开始了 - 要判断
combo not in res
才append
到res
中去
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def helper(remain, combi, idx):
if remain < 0:
return
if remain == 0 and combi not in res:
res.append(combi)
return
if idx >= len(candidates):
return
helper(remain, combi, idx+1)
helper(remain-candidates[idx], combi+[candidates[idx]], idx+1)
res = []
candidates.sort()
helper(target, [], 0)
return res