I have a working solution for a problem found here. After writing it, I noticed I have the exact same statement in both parts of the if/else:
public boolean groupSum6(int start, int[] nums, int target) {
if(start >= nums.length) return target == 0;
int next = start + 1;
int cur = nums[start];
if(cur == 6) return groupSum6(next, nums, target - cur);
return groupSum6(next, nums, target - cur) || groupSum6(next, nums, target);
}
After a little retooling, I was able to 'simplify' the problem to this:
public boolean groupSum6(int start, int[] nums, int target) {
if(start >= nums.length) return target == 0;
int next = start + 1;
int cur = nums[start];
if(cur != 6) {
boolean success = groupSum6(next, nums, target);
if(success) return true;
}
return groupSum6(next, nums, target - cur);
}
I definitely prefer the second solution, even though it is a bit more verbose. My question is, is there a way to simplify this even further? Something seems off to me about having an if statement that returns true, but I might just be over analyzing the problem. I ask solely for improving my logic simplification abilities, not because I think it is something that would be necessary to do.
Aucun commentaire:
Enregistrer un commentaire