Jaspreet singhgeeksforgeeks.org ...
Given an array arr[] of size N, generate the sum of every possible subset.
Return all subset sums.
Every element has only two choices:
Include it
Exclude it
For N elements:
2 × 2 × 2 × ... N times
which gives:
2^N subsets
We recursively explore both choices for every element and calculate the sum formed.
Whenever you see:
Think:
Recursion + Backtracking
Example:
arr = [2,3]
0
/ \
+2 skip
/ \ / \
+3 skip +3 skip
5 2 3 0
Subset sums:
5 2 3 0
import java.util.*;
class Solution {
ArrayList<Integer> subsetSums(int[] arr) {
ArrayList<Integer> ans = new ArrayList<>();
solve(0, 0, arr, ans);
Collections.sort(ans);
return ans;
}
private void solve(int index,
int sum,
int[] arr,
ArrayList<Integer> ans) {
if (index == arr.length) {
ans.add(sum);
return;
}
// Pick
solve(index + 1,
sum + arr[index],
arr,
ans);
// Not Pick
solve(index + 1,
sum,
arr,
ans);
}
}
arr = [1,2]
Pick 1
Pick 2 -> 3
Skip 2 -> 1
Skip 1
Pick 2 -> 2
Skip 2 -> 0
[0,1,2,3]
For every element we have exactly two choices:
Take it
Don't take it
Exploring both choices guarantees that every subset is generated exactly once.
| Metric | Complexity |
|---|---|
| Time Complexity | O(2^N) |
| Space Complexity | O(N) |
Reason:
2^N subsets exist
and recursion depth is:
N
For each element, recursively explore both possibilities—pick and not pick. When we reach the end of the array, the accumulated sum represents one subset sum.
Generate All Subsets
+
Pick / Not Pick
=> Backtracking
=> Recursion