给定一个数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用一次。
说明:
示例 1:
输入: candidates =[10,1,2,7,6,1,5]
, target =8
, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]
C++
class Solution {
public:
void DFS(vector& candidates, set>& res, vector& tmp, int target, int k, int sum)
{
if(sum==target)
{
res.insert(tmp);
return;
}
else if(sum>target)
{
return;
}
for(int i=k;i> combinationSum2(vector& candidates, int target)
{
sort(candidates.begin(),candidates.end());
set> res;
vector tmp;
int sum=0;
DFS(candidates,res,tmp,target,0,sum);
return vector>(res.begin(),res.end());
}
};
python
class Solution:
def DFS(self, candidates, st, tmp, target, k, su):
if su==target:
if tmp not in st:
st.append(tmp.copy())
return
elif su>target:
return
for i in range(k,len(candidates)):
su+=candidates[i]
tmp.append(candidates[i])
self.DFS(candidates,st,tmp,target,i+1,su)
del tmp[-1]
su-=candidates[i]
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
st=[]
tmp=[]
su=0
self.DFS(candidates,st,tmp,target,0,su)
return st