我认为是 O(3^n),有什么想法吗?此方法查找给定数字是否是给定集合的任何子集的总和(overloads boolean isSumOf(int[]s,int n))。如果目标等于 0 或消耗集合中的当前数字(或不消耗)并再次尝试,则该方法在每个递归调用中进行检查,而 target>0 并且我们还没有耗尽数组。
* @param set a given set of natural numbers.
* @param target the number.
* @param i where we are in the set.
* @return true if we reached target, else returns false.
**/
private static boolean isSumOf(int[] set,int target,int i)
{
// Found the set if we are now at 0.
boolean isSum = (target==0);
// Look no further if no more to try.
if ( target > 0 )
{
// Look no further if we've exhausted the array.
if ( i < set.length )
{
// Try or consume this number in the set (or not) and try again.
isSum = isSumOf(set, target - set[i], i) // Consume the current number in the set and try again recursively.
|| isSumOf(set, target - set[i], i+1) // Consume the current number in the set and avdance to rhe next number.
|| isSumOf(set, target, i+1); // Try the current number and avance to the next number in the set.
}
}
return isSum;