Last active
December 11, 2016 04:37
-
-
Save kirtan403/78336d0932c8d54391b018e5433eeaae to your computer and use it in GitHub Desktop.
Solving Subset Sum Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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