開始通過編號線
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