找出递归函数的时间复杂度

时间:2012-09-20 01:10:14

标签: algorithm recursion time-complexity

分配是为了表明在后续递归函数的最坏情况下,时间复杂度为Ω(2 max(n,m))。

假设如下:

  • n = w1len(单词w1的长度),
  • m = w2len(单词w2的长度)

这是代码

int dist(String w1, String w2, int w1len, int w2len) {
    if (w1len == 0) {
        return w2len;
    }
    if (w2len == 0) {
        return w1len;
    }   
    int res = dist(w1, w2, w1len - 1, w2len - 1) + (w1.charAt(w1len - 1) == w2.charAt(w2len - 1) ? 0 : 1);      
    int addLetter = dist(w1, w2, w1len - 1, w2len) + 1;
    if (addLetter < res)
        res = addLetter;
    int deleteLetter = dist(w1, w2, w1len, w2len - 1) + 1;
    if (deleteLetter < res)
        res = deleteLetter;

    return res;
}

1 个答案:

答案 0 :(得分:1)

尝试为该函数绘制调用树。 它是什么样子的? 你能估计一下dist函数的调用次数吗?

相关问题