-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathCombinationSum
More file actions
114 lines (97 loc) · 2.33 KB
/
CombinationSum
File metadata and controls
114 lines (97 loc) · 2.33 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//PROBLEM STATEMENT-
Given an array of integers and a sum B, find all unique combinations in the array where the sum is equal to B. The same number may be chosen from the array any number of times to make B.
Note:
1. All numbers will be positive integers.
2. Elements in a combination (a1, a2, …, ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
3. The combinations themselves must be sorted in ascending order.
Example 1:
Input:
N = 4
arr[] = {7,2,6,5}
B = 16
Output:
(2 2 2 2 2 2 2 2)
(2 2 2 2 2 6)
(2 2 2 5 5)
(2 2 5 7)
(2 2 6 6)
(2 7 7)
(5 5 6)
Example 2:
Input:
N = 11
arr[] = {6,5,7,1,8,2,9,9,7,7,9}
B = 6
Output:
(1 1 1 1 1 1)
(1 1 1 1 2)
(1 1 2 2)
(1 5)
(2 2 2)
(6)
//SOURCE CODE-
#include <bits/stdc++.h>
using namespace std;
class Solution
{
void calSum(vector<int> A, int sum, vector<int> &temp, int index, vector<vector<int>> &res)
{
if(sum == 0)
{
res.push_back(temp);
return;
}
for(int i = index; i < A.size(); i++)
{
if(sum - A[i] >= 0)
{
temp.push_back(A[i]);
sum = sum - A[i];
calSum(A, sum, temp, i, res);
sum = sum + A[i];
temp.pop_back();
}
}
}
public:
vector<vector<int>> combinationSum(vector<int> &A, int sum)
{
sort(A.begin(), A.end());
A.erase(unique(A.begin(), A.end()), A.end());
vector<vector<int>> res;
vector<int> temp;
calSum(A, sum, temp, 0, res);
return res;
}
};
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> A;
for(int i=0;i<n;i++){
int x;
cin>>x;
A.push_back(x);
}
int sum;
cin>>sum;
Solution ob;
vector<vector<int>> result = ob.combinationSum(A, sum);
if(result.size()==0){
cout<<"Empty";
}
for(int i=0;i<result.size();i++){
cout<<'(';
for(int j=0;j<result[i].size();j++){
cout<<result[i][j];
if(j<result[i].size()-1)
cout<<" ";
}
cout<<")";
}
cout<<"\n";
}
}