给定一个无重复元素的数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的数字可以无限制重复被选取。
说明:
target
)都是正整数。示例 1:
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:
输入: candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
给定一个数组 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]
]
39
class Solution {
public:
vector> res;
vector candidates;
vector path;
void DFS(int start,int target){
if(target==0){
res.push_back(path);
return;
}
for(int i=start;i=0){
path.push_back(candidates[i]);
DFS(i,target-candidates[i]);
path.pop_back();
}
}
}
vector> combinationSum(vector& candidates, int target) {
this->candidates = candidates;
DFS(0,target);
return res;
}
};
40
class Solution {
public:
vector> res;
vector path;
vector candidates;
void DFS(int start,int target){
if(target==0){
res.push_back(path);
return;
}
for(int i=start;i start && candidates[i] == candidates[i - 1] && target - candidates[i] >= 0)
continue;
if(target-candidates[i]>=0){
path.push_back(candidates[i]);
DFS(i+1,target-candidates[i]);
path.pop_back();
}
}
}
vector> combinationSum2(vector& candidates, int target) {
sort(candidates.begin(), candidates.end());
this->candidates = candidates;
DFS(0,target);
return res;
}
};