Reputation: 2326
The question is about finding if there exists a subset in an array of ints that sums to a target with following tweaks
There is a
Standard solution
/*
* 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 with these additional constraints:
* all multiples of 5 in the array must be included in the group.
* If the value immediately following a multiple of 5 is 1,
* it must not be chosen. (No loops needed.)
*
* groupSum5(0, {2, 5, 10, 4}, 19) → true
* groupSum5(0, {2, 5, 10, 4}, 17) → true
* groupSum5(0, {2, 5, 10, 4}, 12) → false
* groupSum5(0, {3, 5, 1}, 9) → false
* groupSum5(0, {2, 5, 4, 10}, 12) → false
* groupSum5(0, {3, 5, 1}, 5) → true
* groupSum5(0, {1, 3, 5}, 5) → true
* groupSum5(0, {1}, 1) → true
*/
public boolean groupSum5(int start, int[] nums, int target) {
if (start >= nums.length) return (target == 0);
if (nums[start] % 5 == 0) {
if (start < nums.length - 1 && nums[start + 1] == 1){
return groupSum5(start + 2, nums, target - nums[start]);
}
return groupSum5(start + 1, nums, target- nums[start]);
}
return groupSum5(start + 1, nums, target - nums[start])
|| groupSum5(start + 1, nums, target);
}
My Approach
public boolean groupSum5(int start, int[] nums, int target) {
final int len = nums.length;
if (start == len) {
return target == 0;
}
if (start > 0 && nums[start] == 1 && (nums[start- 1] % 5) == 0 ) {
return groupSum5(start + 1, nums, target);
}
if (groupSum5(start + 1, nums, target - nums[start])) {
return true;
} if ((nums[start] % 5) != 0
& groupSum5(start + 1, nums, target)) {
return true;
}
return false;
}
Which one of the above 2 fares better in terms of time complexity?
If I am not mistaken the standard solution's or the first solution's complexity is greater than exponential (3^n) ? I guess if we take the recursive calls into account would it be correct to say that the complexity is (4^n)?
Upvotes: 0
Views: 90
Reputation: 58221
Your code is wrong I think. groupSum5(0, [0, 1, 1], 1) returns false with your code, because both 1s are excluded. Both the correct groupSum5 and yours are O(2^n) in the worst case. Although groupSum5 appears textually 4 times in the first piece of code only 2 of those calls can ever happen in a single stack frame
Upvotes: 1