fork download
  1. // Iterative C++ program to print sums of all
  2. // possible subsets.
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Prints sums of all subsets of array
  7. void subsetSums(int arr[], int n)
  8. {
  9. vector<int> a;
  10. int i=0;
  11. // There are totoal 2^n subsets
  12. long long total = 1<<n;
  13.  
  14. // Consider all numbers from 0 to 2^n - 1
  15. for (long long i=0; i<total; i++)
  16. {
  17. long long sum =0;
  18.  
  19. // Consider binary reprsentation of
  20. // current i to decide which elements
  21. // to pick.
  22. for (int j=1; j<n; j++)
  23. if (i & (1<<j))
  24. sum += arr[j];
  25.  
  26. // Print sum of picked elements.
  27. a.push_back(sum);
  28. }
  29. for(auto it=a.begin();it!=a.end();it++)
  30. cout << *it<< " ";
  31. }
  32.  
  33. // Driver code
  34. int main()
  35. {
  36. int arr[] = {5, 4, 3};
  37. int n = sizeof(arr)/sizeof(arr[0]);
  38.  
  39. subsetSums(arr, n);
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0s 4396KB
stdin
Standard input is empty
stdout
0 0 4 4 3 3 7 7