import java.util.Arrays; // From http://codingbat.com/prob/p138907 public class Group5Sum { public static boolean groupSum5(int start, int[] nums, int target) { if (start >= nums.length) return target == 0; int val = nums[start]; if(val % 5 == 0) { if(start+1 < nums.length && nums[start+1]==1) return groupSum5(start+2,nums,target - val); else return groupSum5(start+1,nums,target - val); } else { boolean res = groupSum5(start+1,nums,target-val); if(!res) res = groupSum5(start+1,nums,target); return res; } } public static void test(int[] arr,int sum) { boolean res = groupSum5(0,arr,sum); System.out.printf("groupSum5(%s,%d)->%s%n",Arrays.toString(arr),sum,res ? "true" : "false"); } public static void main(String[] args) { test(new int[]{2,1,5},7); test(new int[]{5,1,1},7); test(new int[]{5,1,1,1},7); test(new int[]{5,1,2},7); } }