Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:13
Show Gist options
  • Save dmnugent80/65b75fcca0549d38d0ba to your computer and use it in GitHub Desktop.
Save dmnugent80/65b75fcca0549d38d0ba to your computer and use it in GitHub Desktop.
All sub-sets that sum to zero
/*
Print all subset of a given set which sums up to ZERO
{8,3,5,1,-4,-8}
so ans will be : {8,-8}
{3,5,-8}
{3,1,-4}
*/
import java.util.*;
public class SubsetSumZero
{
private static Stack<Integer> stk;
public static void printSets(int[] a) {
stk = new Stack<Integer>();
Arrays.sort(a);
printSets(a, 0, 0);
}
private static void printSets(int[] a, int hi, int sum) {
// Check the sum
if (sum == 0 && hi > 0){
// print the set
System.out.print("( ");
for (int y : stk){
System.out.print(y + " ");
}
System.out.println(" )");
}
// Recursion - check for every higher index
for (int k=hi; k < a.length; k++) {
int x = a[k];
stk.push(x); // add to the stack
printSets(a, k+1, sum+x);
stk.pop(); // remove from the stack
}
}
public static void main(String[] args)
{
int[] array = {8,3,5,1,-4,-8};
printSets(array);
}
}
/*Output:
( -8 -4 1 3 8 )
( -8 3 5 )
( -8 8 )
( -4 1 3 )
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment