Skip to content

Commit b27316f

Browse files
authored
Merge pull request kothariji#604 from Kowsihan-sk/backTracking
added combination sum in Back tracking
2 parents cbb72a1 + 0c2ead9 commit b27316f

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

Backtracking/Combination_sum_1.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
void dfs(int ind, int t, vector<int> v, vector<int> &ar, vector<vector<int>> &ans){
4+
if(t < 0) return;
5+
if(t == 0){
6+
ans.push_back(v);
7+
return;
8+
}
9+
if(ind < 0) return;
10+
11+
if(ar[ind] <= t){
12+
v.push_back(ar[ind]);
13+
dfs(ind, t - ar[ind], v, ar, ans);
14+
v.pop_back();
15+
}
16+
17+
dfs(ind - 1, t, v, ar, ans);
18+
19+
}
20+
21+
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
22+
vector<vector<int>> ans;
23+
// sort(candidates.begin(), candidates.end());
24+
25+
dfs(candidates.size() - 1, target, {}, candidates, ans);
26+
27+
return ans;
28+
}
29+
};

Backtracking/Combination_sum_2.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
void dfs(int ind, int t, vector<int> v, vector<int> &ar, vector<vector<int>> &ans){
4+
if(t < 0) return;
5+
if(t == 0){
6+
ans.push_back(v);
7+
return;
8+
}
9+
if(ind >= ar.size()) return;
10+
11+
for(int i = ind; i < ar.size(); i++){
12+
if((i != ind && ar[i] == ar[i-1] ) || ar[i] > t) continue;
13+
v.push_back(ar[i]);
14+
dfs(i + 1, t - ar[i], v, ar, ans);
15+
v.pop_back();
16+
}
17+
18+
}
19+
20+
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
21+
vector<vector<int>> ans;
22+
sort(candidates.begin(), candidates.end());
23+
24+
dfs(0, target, {}, candidates, ans);
25+
26+
return ans;
27+
}
28+
};

0 commit comments

Comments
 (0)