Leetcode 40. Combination Sum II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Combination Sum II

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
set<vector<int>> s;
sort(candidates.begin(), candidates.end());
vector<int> combination;
combinationSum2(s, candidates, combination, target, 0, 0);
return vector<vector<int>>(s.begin(), s.end());
}


private:
void combinationSum2(set<vector<int>>& result, vector<int>& candidates, vector<int>& combination, int& target, int sum, int begin) {
if(sum > target) {
return;
}
if(sum == target) {
result.insert(combination);
return;
}
for(int i = begin; i < candidates.size(); i++) {
combination.push_back(candidates[i]);
combinationSum2(result, candidates, combination, target, sum + candidates[i], i + 1);
combination.pop_back();
}
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
set<vector<int>> s;
sort(candidates.begin(), candidates.end());
vector<int> combination;
combinationSum2(s, candidates, combination, target, 0, 0);
return vector<vector<int>>(s.begin(), s.end());
}


private:
void combinationSum2(set<vector<int>>& result, vector<int>& candidates, vector<int>& combination, int& target, int sum, int begin) {
if(sum > target) {
return;
}
if(sum == target) {
result.insert(combination);
return;
}
for(int i = begin; i < candidates.size(); i++) {
if(sum + candidates[i] > target) {
break;
}
combination.push_back(candidates[i]);
combinationSum2(result, candidates, combination, target, sum + candidates[i], i + 1);
combination.pop_back();
}
}
};
  • Version 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> result;
sort(candidates.begin(), candidates.end());
vector<int> combination;
combinationSum2(result, candidates, combination, target, 0, 0);
return result;
}


private:
void combinationSum2(vector<vector<int>>& result, vector<int>& candidates, vector<int>& combination, int& target, int sum, int begin) {
if(sum > target) {
return;
}
if(sum == target) {
result.push_back(combination);
return;
}
for(int i = begin; i < candidates.size(); i++) {
if(sum + candidates[i] > target) {
break;
}
if(i > begin && candidates[i] == candidates[i - 1]) {
continue;
}
combination.push_back(candidates[i]);
combinationSum2(result, candidates, combination, target, sum + candidates[i], i + 1);
combination.pop_back();
}
}
};

Reference

  1. https://leetcode.com/problems/combination-sum-ii/description/
如果有收获,可以请我喝杯咖啡!