/** * A recursion demo using a helper method. */ public class HasSubsetSum { /** * The primary method to check whether some subset of a * sum to target. Just a wrapper around the helper method * that actually does the recursive work. */ public static boolean hasSubsetSum(int[] a, int target) { return subsetHelper(a, target, 0, 0); } /** * The recursive helper method for hasSubsetSum. Uses extra parameters * to track all needed information across recursive calls. */ private static boolean subsetHelper(int[] a, int target, int nextIndex, int sumSoFar) { if (sumSoFar == target) { return true; } else if (sumSoFar > target) { return false; } else if (nextIndex == a.length) { return false; } else { boolean with = subsetHelper(a, target, nextIndex + 1, sumSoFar + a[nextIndex]); boolean without = subsetHelper(a, target, nextIndex + 1, sumSoFar); return with || without; } } // test the method public static void main(String[] args) { int[] vals = {3, 2, 7, 3, 10}; System.out.println("13 possible? " + hasSubsetSum(vals, 13)); System.out.println("14 possible? " + hasSubsetSum(vals, 14)); } }