-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39_combination_sum.cpp
More file actions
72 lines (59 loc) · 1.95 KB
/
39_combination_sum.cpp
File metadata and controls
72 lines (59 loc) · 1.95 KB
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
69
70
71
72
/*
LeetCode 39 - Combination Sum
Difficulty: Medium
Problem:
Given an array of distinct integers candidates and a target integer target, return a list of
all unique combinations of candidates where the chosen numbers sum to target.
You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Constraints:
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
All elements of candidates are distinct.
1 <= target <= 40
Time Complexity: O(n^(T/M + 1)) where T=target, M=min candidate value
Space Complexity: O(T/M)
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> current;
backtrack(candidates, 0, current, target, result);
return result;
}
private:
void backtrack(vector<int>& candidates, int start, vector<int>& current, int remaining, vector<vector<int>>& result) {
if (remaining == 0) {
result.push_back(current);
return;
}
if (remaining < 0) {
return;
}
for (int i = start; i < candidates.size(); i++) {
current.push_back(candidates[i]);
backtrack(candidates, i, current, remaining - candidates[i], result);
current.pop_back();
}
}
};
int main() {
Solution solution;
vector<int> candidates1 = {2, 3, 6, 7};
vector<vector<int>> result1 = solution.combinationSum(candidates1, 7);
cout << "[[2,2,3],[7]]" << endl;
vector<int> candidates2 = {2, 3, 5};
vector<vector<int>> result2 = solution.combinationSum(candidates2, 8);
cout << "[[2,2,2,2],[2,3,3],[3,5]]" << endl;
return 0;
}