开始通过编号线
public static boolean groupSum1(int start, int[] nums, int target)
{
1. if (start >= nums.length) return (target == 0);
2. if (groupSum1(start + 1, nums, target - nums[start])) return true;
3. if (groupSum1(start + 1, nums, target)) return true;
4. return false;
}
这里的执行(假设这是你所要求的):
1 call groupSum1(0, {10, 8, 6}, 16)
1. 0 < 3 next
2 call groupSum1(1, {10, 8, 6}, 6)
1. 1 < 3 next
3 call groupSum1(2, {10, 8, 6}, -2)
1. 2 < 3 next
4 call groupSum1(3, {10, 8, 6}, -8)
1. 3 == 3 return false to call 3
back to call 3 in line 2.
5 call groupSum1(3, {10, 8, 6}, -2)
1. 3 == 3 return false to call 3
back to call 3 in line 3.
return false to call 2
back to call 2 in line 2.
6 call groupSum1(2, {10, 8, 6}, 6)
2 < 3 next
7 call groupSum1(3, {10, 8, 6}, 0)
3 == 3 return true to call 6
back to call 6 in line 2.
return true to call 2
back to call 2 in line 3.
return true to call 1
back to call 1 in line 2.
return true
在递归调用前面的数字只是一个指标我用来跟踪深度。我希望这是可以理解的。
你是什么意思的“跟踪”吗?你的目标是什么? – 2012-02-23 21:56:58
这是NP完全问题,对不对? – JProgrammer 2012-02-23 22:03:07
@JProgrammer问题陈述有点给了验证者。另外http://en.wikipedia.org/wiki/Subset_sum_problem – 2012-02-23 22:17:00