-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path40. 组合总和 II.cc
65 lines (58 loc) · 1.85 KB
/
40. 组合总和 II.cc
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
vector<vector<int>> res;
int target;
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
{
this->target = target;
sort(candidates.begin(), candidates.end());
backtrace(candidates, vector<int>(), 0, 0);
return res;
}
void backtrace(vector<int> &candidates, vector<int> subres, int index, int sum)
{
if(sum == target)
{
res.push_back(move(subres));
return ;
}
for(int i=index; i<candidates.size() && sum+candidates[i]<=target; ++i)
{
/* 在同层递归中,对于重复元素,不再决策,直接跳过 */
if(i>index && candidates[i] == candidates[i-1]) continue;
subres.push_back(candidates[i]);
backtrace(candidates, subres, i+1, sum+candidates[i]);
subres.pop_back();
}
}
};
/* 优化 */
class Solution {
vector<vector<int>> res;
vector<int> path; /* 使用一个数组,backtrace参数不再使用subres */
int target;
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
{
this->target = target;
sort(candidates.begin(), candidates.end());
backtrace(candidates, 0, 0);
return res;
}
void backtrace(vector<int> &candidates, int index, int sum)
{
if(sum == target)
{
res.push_back(path);
return ;
}
for(int i=index; i<candidates.size() && sum+candidates[i]<=target; ++i)
{
/* 在同层递归中,对于重复元素,不再决策,直接跳过 */
if(i>index && candidates[i] == candidates[i-1]) continue;
path.push_back(candidates[i]);
backtrace(candidates, i+1, sum+candidates[i]);
path.pop_back();
}
}
};