【发布时间】:2015-11-03 02:52:51
【问题描述】:
根据这个post,我们知道如何确定递归函数的复杂度。
但是,对于下面的代码,
const int N = 100, W = 100000;
int p[N][W + 1]; // the values of element in the array p are 0, 1, 2.
int output[N];
void find_path(int n, int w, int k) {
if (n < 0) {
for (int i=0; i<k; ++i) cout << output[i];
return;
}
if (p[n][w] == 0) {
find_path(n-1, w, k); // the 1st branch
}
else if (p[n][w] == 1) {
output[k] = n;
find_path(n-1, w-weight[n], k+1); // the 2nd branch
}
else if (p[n][w] == 2) {
output[k] = n; // the 3rd branch
find_path(n-1, w-weight[n], k+1);
find_path(n-1, w, k);
}
}
这是我的分析:
T(n) = T(n-1) + a // the 1st branch
T(n-1) + b // the 2nd branch
2*T(n-1) + c // the 3rd branch
乍一看,第3个分支比其他两个分支耗时,我可以忽略第1个和第2个分支吗?,所以复杂度可能是T(n)=2*T(n-1),结果是O(2^n),我说的对吗?
此外,如果第二个分支中还有一个 find_path 调用会怎样
else if (p[n][w] == 1) {
output[k] = n;
find_path(n-1, w-weight[n], k+1); // the 2nd branch
find_path(n-1, w, k+1);
}
这种情况下如何计算时间复杂度?
【问题讨论】:
标签: algorithm recursion big-o time-complexity