-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSumII.cpp
More file actions
38 lines (33 loc) · 988 Bytes
/
CombinationSumII.cpp
File metadata and controls
38 lines (33 loc) · 988 Bytes
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
/***
* DFS
* 同Combination Sum
* 不同的是每个数只能选一次,若当前数等于前一个数,而前一个数又没有选,则当前数也不能选
***/
class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
std::sort(num.begin(), num.end());
vector<int> path;
dfs(num, target, 0, path);
return vvcoms;
}
private:
vector<vector<int> > vvcoms;
void dfs(const vector<int> &num, int target, int start, vector<int> &path)
{
if (0 == target)
{
vvcoms.push_back(path);
return;
}
for (int i = start; (i < num.size()) && (target >= num[i]); ++i)
{
if ((i > start) && (num[i] == num[i-1])) // not choose num[i-1]
continue;
path.push_back(num[i]);
dfs(num, target-num[i], i+1, path); // i+1, check next num
path.pop_back();
}
return;
}
};