Advertisement
Guest User

Untitled

a guest
Aug 29th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. public static boolean findSumFromList (ArrayList<Integer> set, Integer sum, ArrayList<Integer> result) {
  2. // if sum=0, we have found a solution
  3. if (sum == 0) {
  4. System.out.println(result);
  5. return true;
  6. }
  7.  
  8. // Sum < 0. No point going forward in the path
  9. if (sum < 0)
  10. return false;
  11.  
  12. // Reached at the end of a path and this path is not the solution
  13. if (set.size() == 0 && sum != 0)
  14. return false;
  15.  
  16.  
  17. ArrayList<Integer> newSet = new ArrayList<>(set);
  18. newSet.remove(0);
  19.  
  20. // Select the first element
  21. System.out.println("Left: Picking up " + set.get(0));
  22. result.add(set.get(0));
  23. if (getSum(newSet, sum - set.get(0), result)) {
  24. return true;
  25. }
  26.  
  27. // Reject the first element
  28. System.out.println("Right: NOT Picking up " + set.get(0));
  29. result.remove(result.size()-1);
  30. if (getSum(newSet, sum, result)) {
  31. return true;
  32. }
  33.  
  34. return false;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement