[英]Java - Recursive solution for subset sum
我被告知要编写一个递归函数,该函数采用起始索引、整数数组和目标总和,您的目标是找出整数数组的子集是否与目标总和相加。
我给出的例子是 groupSum(0, {2, 4, 8}, 10) 应该返回 true 因为 2 和 8 加起来是目标,10。到目前为止我能做的只是基本情况。
public boolean groupSum(int start, int[] nums, int target) {
if (nums.length == 0)
{
return false;
}
else if (start == nums.length - 1)
{
return nums[start] == target;
}
else
{
?????
}
}
我不知道我应该在哪里进行实际的递归调用。 由于我无法在调用之间传递总和,因此在达到目标之前,我不知道如何在每个递归调用中添加一个数字。 另外,就像示例中所示,我不知道如何让我的代码意识到当一个数字不起作用并跳过它时,就像示例中对 4 所做的那样。我正在考虑我应该减去从 int target 一次一个数字,然后使用新的起点和 target 的新值递归调用该方法,但我不知道如何使用它来查看是否存在有效的子集。
我将不胜感激任何可以帮助我了解如何解决此问题以便我可以完成它的帮助。 谢谢!
这是一个工作版本。 请参阅代码中的注释以获取解释。
public static boolean recursiveSumCheck(int target, int[] set) {
//base case 1: if the set is only one element, check if element = target
if (set.length == 1) {
return (set[0] == target);
}
//base case 2: if the last item equals the target return true
int lastItem = set[set.length - 1];
if (lastItem == target) {
return true;
}
//make a new set by removing the last item
int[] newSet = new int[set.length - 1];
for (int newSetIndex = 0; newSetIndex < newSet.length; newSetIndex++) {
newSet[newSetIndex] = set[newSetIndex];
}
//recursive case: return true if the subset adds up to the target
// OR if the subset adds up to (target - removed number)
return (recursiveSumCheck(target, newSet) || recursiveSumCheck(target - lastItem, newSet));
}
动态规划 。 也许这会对您有所帮助。
这应该根据给定的条件工作。 初始值start = 0
boolean subsetSum(int start, int[] nums, int target) {
// target is the sum you want to find in the nums array
if (target == 0) return true;
if (start > nums.length-1 || nums.length == 0)
return false;
if (nums[start] > target)
return subsetSum(start+1, nums, target);
return subsetSum(start+1, nums, target) || subsetSum(start+1, nums, target - nums[start]);
}
如您所指出的,您可以更改目标,而不用传递总和。 一旦目标为零,您就知道您已找到解决方案(通过选择其余项目的任何成员)。
因此,在伪代码中:
hasMembersThatSumTo(list, total):
if total == 0
return true
else if total < 0 or list is empty
return false
else
int first = list.pop
return hasMembersThatSumTo(list, total - first)
or hasMembersThatSumTo(list, total)
“或”语句中的两种情况正在寻找这种情况,即当前元素在总和中或不在总和中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.