Guest User

Untitled

a guest
Feb 25th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. package com.shaaslam.recurrsion;
  2.  
  3. /*
  4. * Given an array of ints, is it possible to choose a group of some of the ints,
  5. * such that the group sums to the given target?
  6. * This is a classic backtracking recursion problem.
  7. * Once you understand the recursive backtracking strategy in this problem,
  8. * you can use the same pattern for many problems to search a space of choices.
  9. * Rather than looking at the whole array, our convention is to consider the part of the array
  10. * starting at index start and continuing to the end of the array.
  11. * The caller can specify the whole array simply by passing start as 0.
  12. * No loops are needed -- the recursive calls progress down the array.
  13.  
  14. Example:
  15. groupSum(0, [2, 4, 8], 10) → true
  16. groupSum(0, [2, 4, 8], 14) → true
  17. groupSum(0, [2, 4, 8], 9) → false
  18. */
  19. public class GroupSum {
  20.  
  21. public static boolean groupSum(int index, int[] arr, int desiredSum) {
  22. if(desiredSum == 0)
  23. return true;
  24. else {
  25. for(int i = index; i < arr.length; i++) {
  26. // choose;
  27. int n = arr[i];
  28.  
  29. //explorer
  30. boolean result = groupSum(i + 1, arr, desiredSum-n);
  31. if(result)
  32. return true;
  33. }
  34. }
  35. return false;
  36. }
  37. public static void main(String[] args) {
  38. System.out.println(groupSum(0, new int[]{2,4,8}, 10));
  39. System.out.println(groupSum(0, new int[]{2,4,8}, 14));
  40. System.out.println(groupSum(0, new int[]{2,4,8}, 9));
  41. }
  42.  
  43. }
Add Comment
Please, Sign In to add comment