leetcode39 40組合總和
描述
39. 組合總和
給定一個無重複元素的數組 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]
]
40. 組合總和 II
給定一個數組 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<vector<int>> res;
vector<int> candidates;
vector<int> path;
void DFS(int start,int target){
if(target==0){
res.push_back(path);
return;
}
for(int i=start;i<candidates.size();i++){
if(target-candidates[i]>=0){
path.push_back(candidates[i]);
DFS(i,target-candidates[i]);
path.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
this->candidates = candidates;
DFS(0,target);
return res;
}
};
40
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<int> candidates;
void DFS(int start,int target){
if(target==0){
res.push_back(path);
return;
}
for(int i=start;i<candidates.size();i++){
if (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<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
this->candidates = candidates;
DFS(0,target);
return res;
}
};