简体   繁体   中英

What is the time complexity of my recursive method with dynamic programming

I'm working on an algorithm on getting the f(n) of a set 'S'. It is defined as

图片

example: f(4) = S(4) + f(3) + f(2) + f(1) + f(0)

this is my pseudocode

func solve(int k, int[] s, int[] memo)
{
    if(k==0) //base case
        return s[0]
    if(memo[k] == -1) 
    {
        var nTemp = 0 
        for(int i=0; i < k; i++) 
            nTemp = (nTemp + solve(i, s, memo)) 
        memo[k] = (nTemp + s[k]) 
    }
    return memo[k]
}

I'm not sure about it's time complexity though, I think it is O(n) but i'm not sure.

Let's consider how many operations solve has to perform starting from k = 1 :

k = 1: memo[1] = s[0] + s[1] -> 1 sum
k = 2: memo[2] = memo[0] + memo[1] + s[2] -> 2 sums
...
k = m: memo[s] = memo[0] + memo[1] + ... + s[m] -> m sums  

So actually, the number of operations is 1 + 2 + .. + k = (k + 1)*k/2 ~ k*k . Hence, the total time complexity is O(k^2) .

However, if values up to k-1 are already cached in memo and we need to calculate f(k) then the time complexity is O(k) since it's only about summing up memo[i] such that i<k .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM