Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 (getSum(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 (getSum(newSet, sum, result)) {
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement