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 nums[], int n)
  8. {
  9. // There are total 2^n subsets
  10. vector<int> s = {0};//store the sums
  11.  
  12. for (int i = 0; i <n; i++) {
  13. const int v = s.size();
  14. for (int t = 0; t < v; t++) {
  15. s.push_back(s[t] + nums[i]); //add this element with previous subsets
  16. }
  17. }
  18. // Print
  19. for(int i=0;i<s.size();i++)
  20. cout << s[i] << " ";
  21. }
  22.  
  23. // Driver code
  24. int main()
  25. { int n;cin>>n;int a[n];for(auto &p:a){cin>>p;}
  26.  
  27. subsetSums(a, n);
  28. return 0;
  29. }
  30.  
Success #stdin #stdout 0.01s 5292KB
stdin
5
1 -1 10 1 1
stdout
0 1 -1 0 10 11 9 10 1 2 0 1 11 12 10 11 1 2 0 1 11 12 10 11 2 3 1 2 12 13 11 12