簡體   English   中英

如何計算 function 的時間復雜度?

[英]How do I calculate the time complexity of the function?

int coin_row(int[] array, int index, int length)
{
    if (index >= length) //beyond last coin
    {
        return 0;
    }

    int value = array[index];
    if (index >= length - 1) //last coin
    {
        return value;
    }
    else if (index >= length - 2) //second last coin
    {
        return max(value, coin+row(array, index+1);
    }

    return max(value+coin_row(array, index+2,length), coin_row(array, index+1,length));
}

計算這個遞歸function的時間復雜度應該怎么做?

是 O(n)。

看這個:寫一個遞歸關系。 這是T(n) = T(n+1) + O(1)T(l) = 1 第一個等式中的 O(1) 來自 max() function。

因為每一步都需要O(1)次操作,並且有 n 個遞歸調用,其中 n 是長度。 時間復雜度為 O(n*1) = O(n)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM