![]() |
VOOZH | about |
Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum.
Examples:
Input: set[] = {1,2,1}, sum = 3
Output: [1,2],[2,1]
Explanation: There are subsets [1,2],[2,1] with sum 3.Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 30
Output: []
Explanation: There is no subset that add up to 30.
Subset sum can also be thought of as a special case of the 0–1 Knapsack problem. For each item, there are two possibilities:
- Include the current element in the subset and recur for the remaining elements with the remaining Sum.
- Exclude the current element from the subset and recur for the remaining elements.
Finally, if Sum becomes 0 then print the elements of current subset. The recursion’s base case would be when no items are left, or the sum becomes negative, then simply return.
Implementation of the above approach:
Output 1:
[ 2 1 ][ 1 2 ]
Output 2:
There is no such subset
Complexity analysis: