This post is completed by 1 user
|
Add to List |
419. Print all subsets of an array with a sum equal to zero
Objective: Given an array of integers write an algorithm to find all the subsets for which sum is equal to zero. The array contains both positive and negative integers.
Example:
Given Array: [8, 3, 5, 1, -4, -8], required sum: 0 Output: [-8, -4, 1, 3, 8] [-8, 3, 5] [-8, 8] [-4, 1, 3]
Given Array: [3, 1, -4, 2, 0], required sum: 0 Output: [-4, 0, 1, 3] [-4, 1, 3] [0]
Approach:
- Given arrA[].
- Sort the arrA[] in ascending order.
- Start with currSum = 0, startIndex = 0, combinationList=null
- Iterate through i = startIndex to length(arrA[]).
- Add arrA[i] to currSum.
- Put arrA[i] to combinationList.
- Make a recursive call with startIndex=i+1 (to process next elements) and combinationList.
- In tail recursion, backtrack and remove arrA[i] from the combinationList to find more solutions
- Base case: if currSum=0 and combinationList is not empty, Print combinationList.
Output:
Given Array: [8, 3, 5, 1, -4, -8], required sum: 0 [-8, -4, 1, 3, 8] [-8, 3, 5] [-8, 8] [-4, 1, 3]
Reference: https://www.careercup.com/question?id=6130274301640704