Skip to content

Commit 24536f0

Browse files
Added combination sum problem in c++
1 parent 15ab467 commit 24536f0

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// 40. Combination Sum II
2+
// Medium
3+
4+
// 7077
5+
6+
// 175
7+
8+
// Add to List
9+
10+
// Share
11+
// Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
12+
13+
// Each number in candidates may only be used once in the combination.
14+
15+
// Note: The solution set must not contain duplicate combinations.
16+
17+
18+
19+
// Example 1:
20+
21+
// Input: candidates = [10,1,2,7,6,1,5], target = 8
22+
// Output:
23+
// [
24+
// [1,1,6],
25+
// [1,2,5],
26+
// [1,7],
27+
// [2,6]
28+
// ]
29+
// Example 2:
30+
31+
// Input: candidates = [2,5,2,1,2], target = 5
32+
// Output:
33+
// [
34+
// [1,2,2],
35+
// [5]
36+
// ]
37+
38+
39+
// Constraints:
40+
41+
// 1 <= candidates.length <= 100
42+
// 1 <= candidates[i] <= 50
43+
// 1 <= target <= 30
44+
45+
class Solution {
46+
public:
47+
vector<vector<int>>ans;
48+
// map<vector<int>,bool>m;
49+
void solve(vector<int>&arr, int k, int i, vector<int>&subset){
50+
// for(int j=0;j<subset.size();j++)cout<<subset[j]<<" ";
51+
// cout<<k<<"\n";
52+
if(k==0){
53+
// if(!m[subset]){
54+
ans.push_back(subset);
55+
// m[subset]=true;
56+
// }
57+
58+
return;
59+
}
60+
if(k<0 || i>=arr.size())return;
61+
62+
for(int j=i;j<arr.size();j++){
63+
if(i!=j && arr[j]==arr[j-1])continue;
64+
subset.push_back(arr[j]);
65+
solve(arr,k-arr[j],j+1,subset);
66+
subset.pop_back();
67+
}
68+
69+
70+
// solve(arr,k,i+1,subset);
71+
72+
73+
}
74+
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
75+
ans.clear();
76+
// m.clear();
77+
vector<int>subset;
78+
sort(candidates.begin(),candidates.end());
79+
solve(candidates,target,0,subset);
80+
return ans;
81+
}
82+
};

0 commit comments

Comments
 (0)