fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void disp_l( vector<int> &l) {
  5. cout<<"\n";
  6. for(auto x:l) {
  7. cout<<x<<" ";
  8. }
  9. cout<<endl;
  10. }
  11.  
  12. void disp(vector<vector<int>> &ans) {
  13. for(int i=0; i< ans.size(); i++) {
  14. int sum =0;
  15. for(int j=0; j<ans[i].size(); j++) {
  16. cout<< ans[i][j] <<" ";
  17. sum += ans[i][j];
  18. }
  19. cout<<" "<<sum;
  20. cout<<endl;
  21. }
  22. }
  23. //subsetSum(0, n/2,arr, layer, ans, sum);
  24.  
  25. void subsetSum(int i, int n,vector<int> &arr, vector<int> &layer, vector<vector<int>> &ans, int sum) {
  26. if( i== n) {
  27. ans.push_back(layer);
  28. //disp_l(layer);
  29. return;
  30. }
  31. //pick
  32. layer.push_back(arr[i]);
  33. sum+=arr[i];
  34. subsetSum(i+1, n,arr, layer, ans, sum);
  35.  
  36. layer.pop_back();
  37. sum = sum- arr[i];
  38. subsetSum(i+1, n,arr, layer, ans, sum);
  39. }
  40.  
  41.  
  42. int main(){
  43. vector<int> arr = {45, 34, 4, 12, 5, 23};
  44. int n = sizeof(arr)/ sizeof(arr[0]);
  45. //cout<<n;
  46. int sum =0;
  47. vector<int> layer;
  48. vector<vector<int>> ans;
  49. vector<vector<int>> ans1;
  50. subsetSum(0, n/2,arr, layer, ans, sum);
  51. layer.clear();
  52. disp(ans);
  53. cout<<"\n NEW \n";
  54. subsetSum(n/2,n, arr, layer, ans1, 0);
  55. disp(ans1);
  56.  
  57. return 0;
  58.  
  59.  
  60. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
45 34 4  83
45 34  79
45 4  49
45  45
34 4  38
34  34
4  4
 0

 NEW 
12 5 23  40
12 5  17
12 23  35
12  12
5 23  28
5  5
23  23
 0