fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to calculate sums of all subsets
  5. void subsetSums(int nums[], int n) {
  6. // Use a set to store all subset sums (sorted and unique)
  7. set<int> s;
  8. s.insert(0); // Initialize with the sum of the empty subset
  9.  
  10. // Iterate over each element in the array
  11. for (int i = 0; i < n; i++) {
  12. vector<int> current(s.begin(), s.end()); // Copy current elements to iterate safely
  13. for (int sum : current) {
  14. s.insert(sum + nums[i]); // Add current element to each existing subset sum
  15. }
  16. }
  17.  
  18. // Print all subset sums in ascending order
  19. for (int sum : s) {
  20. cout << sum << " ";
  21. }
  22. cout << endl;
  23. }
  24.  
  25. // Driver code
  26. int main() {
  27. int t;cin>>t;
  28. while(t--){
  29. int n;
  30. cin >> n;
  31. int a[n];
  32. for (int i = 0; i < n; i++) {
  33. cin >> a[i];
  34. }
  35.  
  36. subsetSums(a, n);}
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0s 5284KB
stdin
5
5
1 -1 10 1 1
5
-1 -1 -1 -1 -1
2
-1 2
2
7 1
3
1 4 -1
stdout
-1 0 1 2 3 9 10 11 12 13 
-5 -4 -3 -2 -1 0 
-1 0 1 2 
0 1 7 8 
-1 0 1 3 4 5