Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target? This is a classic backtracking recursion problem. Once you understand the recursive backtracking strategy in this problem, you can use the same pattern for many problems to search a space of choices. Rather than looking at the whole array, our convention is to consider the part of the array starting at index start and continuing to the end of the array. The caller can specify the whole array simply by passing start as 0. No loops are needed -- the recursive calls progress down the array.
publicbooleansplitArray(int[] nums) {int total =0;for (int i =0; i <nums.length; i++) { total += nums[i]; }returnsplit(0, nums,0, total);}publicbooleansplit(int idx,int[] nums,int sum,int total) {if (nums.length==0) returntrue;if (idx >=nums.length) returnfalse;if (total - sum == sum) returntrue;if (split(idx +1, nums, sum, total)) returntrue;if (split(idx +1, nums, sum + nums[idx], total)) returntrue;returnfalse;}
splitOdd10
publicbooleansplitOdd10(int[] nums) {// so that the sum of one group is a multiple of 10// and the sum of the other group is odd.int total =0;for (int i =0; i <nums.length; i++) { total += nums[i]; }returndfs(0, total,0, nums);}publicbooleandfs(int idx,int total,int sum,int[] nums) {if (idx >=nums.length) returnfalse;if (nums.length==0) returnfalse;int leftSum = total - sum;if (sum %10==0&& leftSum %2==1) returntrue;if (leftSum %10==0&& sum %2==1) returntrue;if (dfs(idx +1, total, sum, nums)) returntrue;if (dfs(idx +1, total, sum + nums[idx], nums)) returntrue;returnfalse;}