-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcombinationSum.cpp
68 lines (62 loc) · 1.45 KB
/
combinationSum.cpp
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
66
67
68
class Solution
{
vector<vector<int>> result;
public:
void dfs(vector<int> &nums, vector<int> temp, int remain, int start)
{
if (remain < 0)
return;
else if (remain == 0)
result.emplace_back(temp);
else
{
for (int i = start; i < nums.size(); i++)
{
temp.push_back(nums[i]);
dfs(nums, temp, remain - nums[i], i);
temp.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
dfs(candidates, vector<int>(), target, 0);
return result;
}
};
// better
class Solution
{
public:
void generateCombinations(int i, int k, vector<int> &a, vector<int> &tmp, vector<vector<int>> &res)
{
if (i == a.size())
{
tmp.pop_back();
return;
}
if (k < 0)
{
tmp.pop_back();
return;
}
if (k == 0)
{
res.push_back(tmp);
tmp.pop_back();
}
else
{
tmp.push_back(a[i]);
generateCombinations(i, k - a[i], a, tmp, res);
generateCombinations(i + 1, k, a, tmp, res);
}
}
vector<vector<int>> combinationSum(vector<int> &s, int k)
{
vector<int> tmp;
vector<vector<int>> res;
generateCombinations(0, k, s, tmp, res);
return res;
}
};