Skip to content

Instantly share code, notes, and snippets.

@kirtan403
Last active December 11, 2016 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirtan403/78336d0932c8d54391b018e5433eeaae to your computer and use it in GitHub Desktop.
Save kirtan403/78336d0932c8d54391b018e5433eeaae to your computer and use it in GitHub Desktop.
Solving Subset Sum Problem
public static boolean findSumFromList (ArrayList<Integer> set, Integer sum, ArrayList<Integer> result) {
// if sum=0, we have found a solution
if (sum == 0) {
System.out.println(result);
return true;
}
// Sum < 0. No point going forward in the path
if (sum < 0)
return false;
// Reached at the end of a path and this path is not the solution
if (set.size() == 0 && sum != 0)
return false;
ArrayList<Integer> newSet = new ArrayList<>(set);
newSet.remove(0);
// Select the first element
System.out.println("Left: Picking up " + set.get(0));
result.add(set.get(0));
if (findSumFromList(newSet, sum - set.get(0), result)) {
return true;
}
// Reject the first element
System.out.println("Right: NOT Picking up " + set.get(0));
result.remove(result.size()-1);
if (findSumFromList(newSet, sum, result)) {
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment