/** * Recursive subset sum - an example of using a helper method in recursion. */ public class SubsetSum { // the "main" subset sum method - just a wrapper around the helper public static boolean subsetSum(int[] a, int target) { return recSubset(a, target, 0, 0); } // the helper method that does the actual work. // includes extra parameters for the values that recursion needs to track. private static boolean recSubset(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 = recSubset(a, target, nextIndex + 1, sumSoFar + a[nextIndex]); boolean without = recSubset(a, target, nextIndex + 1, sumSoFar); return with || without; } } public static void main(String[] args) { int[] vals = {3, 2, 7, 3, 10}; System.out.println("13 possible? " + subsetSum(vals, 13)); System.out.println("14 possible? " + subsetSum(vals, 14)); } }