#include <bits/stdc++.h>
using namespace std;
void printAllSubsetsRec(int arr[], int n, vector<int> v,
int sum, int B[])
{
if (sum == 0) {
for (auto x : v)
cout << x << " ";
cout << endl;
return;
}
if (n == 0)
return;
printAllSubsetsRec(arr, n - 1, v, sum, B);
v.push_back(arr[n - 1]);
printAllSubsetsRec(arr, n - 1, v, sum - arr[n - 1], B);
}
void printAllSubsets(int arr[], int n, int sum)
{
vector<int> v;
int B[n] = {0};
printAllSubsetsRec(arr, n, v, sum, B);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int arr[] = {1, 4, 9, 25};
int sum = 26;
int n = sizeof(arr) / sizeof(arr[0]);
printAllSubsets(arr, n, sum);
return 0;
}
You can see the v.push_back(a[n-1])
command up there (it's a gfg solutions, I was just trying to understand it), so to understand better whenever the push command runs, I wrote a cout<<a[n-1]
code just to know which elements are inserted in it. But the cout
command gives be nearly all the available elements in the array, whereas when we print the vector (in the top most code where sum==0
) it only prints the subset. Can anyone tell how this works? I am basically trying to print a bit-wise array, so for that I am having difficulty understanding.
Just use cout<<a[n-1]
command after v.push_back(a[n-1]
), you will get a rough idea of what I am talking about.
Aucun commentaire:
Enregistrer un commentaire