![]() |
VOOZH | about |
Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order.
Examples :
Input: arr[] = {2, 3}
Output: 0 2 3 5
Explanation: All subsets of this array are - {{}, {2}, {3}, {2, 3}}, having sums - 0, 2, 3 and 5 respectively.
Input: arr[] = {2, 4, 5}
Output: 0 2 4 5 6 7 9 11
There are total 2n subsets. The idea is to generate a loop from 0 to 2n - 1. For every number, pick all array elements corresponding to 1s in the binary representation of the current number.
Output :
0 5 4 9 3 8 7 12 We can recursively solve this problem. There are total 2n subsets. For every element, we consider two choices, we include it in a subset and we don't include it in a subset. Below is recursive solution based on this idea.
Output :
12 9 8 5 7 4 3 0In this method, while visiting a new element, we take its sum with all previously stored sums. This method stores the sums of all subsets and hence it is valid for smaller inputs.
Output:
0 5 4 9 3 8 7 12 The above-mentioned techniques can be used to perform various operations on sub-sets like multiplication, division, XOR, OR, etc, without actually creating and storing the sub-sets and thus making the program memory efficient.