fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void disp(vector<vector<int>> &ans) {
  5. for(int i=0; i< ans.size(); i++) {
  6. int sum =0;
  7. for(int j=0; j<ans[i].size(); j++) {
  8. cout<< ans[i][j] <<" ";
  9. sum += ans[i][j];
  10. }
  11. cout<<" "<<sum;
  12. cout<<endl;
  13. }
  14. }
  15. //subsetSum(0, n/2,arr, layer, ans, sum);
  16. void subsetSum(int i, int n,vector<int> &arr, vector<int> &layer, vector<vector<int>> &ans, int sum) {
  17. if( i== n) {
  18. ans.push_back(layer);
  19. return;
  20. }
  21. //pick
  22. layer.push_back(arr[i]);
  23. sum+=arr[i];
  24. subsetSum(i+1, n/2,arr, layer, ans, sum);
  25.  
  26. layer.pop_back();
  27. sum = sum- arr[i];
  28. subsetSum(i+1, n/2,arr, layer, ans, sum);
  29. }
  30.  
  31.  
  32. int main(){
  33. vector<int> arr = {45, 34, 4, 12, 5, 23};
  34. int n = sizeof(arr)/ sizeof(arr[0]);
  35. cout<<n;
  36. int sum =0;
  37. vector<int> layer;
  38. vector<vector<int>> ans;
  39. subsetSum(0, n/2,arr, layer, ans, sum);
  40. disp(ans);
  41. return 0;
  42.  
  43.  
  44. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
645  45
 0