Confused by Return in Array Recursion (java) -
given array of ints, possible divide ints 2 groups, sums of 2 groups same. every int must in 1 group or other. write recursive helper method takes whatever arguments like, , make initial call recursive helper splitarray(). (no loops needed.)
this problem coding bat trying figure out. got stuck found solution confused purpose of 1 line , confused final return statement doing. help!
public boolean splitarray(int[] nums) { return splitarrayhelper(nums, 0, new int[nums.length], 0, 0, new int[nums.length], 0, 0); } private boolean splitarrayhelper(int[] nums, int n, int[] split1, int s1, int t1, int[] split2, int s2, int t2) { if (n == nums.length) return t1 == t2; //returns true or false split2[s2] = split1[s1] = nums[n]; // purpose of line? return splitarrayhelper(nums, n + 1, split1, s1 + 1, t1 + nums[n], split2, s2, t2) || splitarrayhelper(nums, n + 1, split1, s1, t1, split2, s2 + 1, t2 + nums[n]); } //i don't know return statement doing. how or statement decided?
the idea have split original array 2 arrays, called , b, every number in original array, number either belong a, or b. keep sum of (group1total) , sum of b (group2total) far.
i write helper below
private static boolean splithelp(int[] nums, int elementcount, int group1total, int group2total) { if (elementcount == nums.length) { return group1total == group2total; } return splithelp(nums, elementcount + 1, group1total+ nums[n], group2total) //the element belongs array || splithelp(nums, n + 1, group1total, group2total+ nums[n]) //or element belongs array b; }
Comments
Post a Comment