![]() |
VOOZH | about |
Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target.
Examples:
Input: arr[] = [1, 2, 3, 3], target = 6
Output: 3
Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3]Input: arr[] = [1, 1, 1, 1], target = 1
Output: 4
Explanation: All the possible subsets are [1], [1], [1] and [1]
Approach:
We can identify a recursive pattern in this problem. There are two state variables:
We consider two cases for recursion:
Exclude the current element: The current element is not included in the subset, and the sum remains unchanged. This corresponds to:
- countSubsets(i + 1, currentSum, target).
Include the current element: The current element is included in the subset, and the sum is updated as currentSum + arr[i]. This corresponds to:
- countSubsets(i + 1, currentSum + arr[i], target)
Recurrence relation:
- countSubsets(i, currentSum, target) = countSubsets(i+1, currentSum, target) + countSubsets(i+1, currentSum + arr[i], target)
Base Case: If i == n (all elements have been processed), return 1 if the currentSumequal to target else 0.
3
Time Complexity: O(2^n), where n is the size of array.
Auxiliary Space: O(n)
Please refer to efficient method to solve the problem using Dynamic Programming.