子集和问题的实现的最坏情况下的时间复杂度是多少?
// Returns true if there is a subset of set[] with sun equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
// If last element is greater than sum, then ignore it
if (set[n-1] > sum)
return isSubsetSum(set, n-1, sum);
/* else, check if sum can be obtained by any of the following
(a) including the last element
(b) excluding the last element */
return isSubsetSum(set, n-1, sum) ||
isSubsetSum(set, n-1, sum-set[n-1]);
}
(A) O(n * 2 ^ n)
(B) O(n ^ 2)
(C) O(n ^ 2 * 2 ^ n)
(D) O(2 ^ n)答案: (D)
说明:以下是子集和问题的给定实现的重复发生
T(n)= 2T(n-1)+ C1
T(0)= C1
其中C1和C2是某些机器特定的常数。
递归的解是O(2 ^ n)
我们可以借助递归树方法看到它
C1
/ \
T(n-1) T(n-1)
C1
/ \
C1 C1
/ \ / \
T(n-2) T(n-2) T(n-2) T(n-2)
C1
/ \
C1 C1
/ \ / \
C1 C1 C1 C1
/ \ / \ / \ / \
If we sum the above tree level by level, we get the following series
T(n) = C1 + 2C1 + 4C1 + 8C1 + ...
The above series is Geometrical progression and there will be n terms in it.
So T(n) = O(2^n)
这个问题的测验