【问题标题】:Time complexity of recursive function with multiple branches具有多个分支的递归函数的时间复杂度
【发布时间】: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


    【解决方案1】:

    是的,你应该取它们的最大值(对于最坏的情况),它对应于第三个分支。因此,您可以忽略第一个和第二个分支。那么,递归是T(n)&lt;=2T(n-1)+O(1),所以T(n)=O(2^n)

    出于同样的原因,您可以“免费”将新调用添加到第二个分支。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-19
      • 2020-10-05
      • 1970-01-01
      • 2018-05-29
      • 2018-08-18
      相关资源
      最近更新 更多