简体   繁体   English

我的动态规划递归方法的时间复杂度是多少

[英]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'.我正在研究一种获取集合“S”的 f(n) 的算法。 It is defined as它被定义为

图片

example: f(4) = S(4) + f(3) + f(2) + f(1) + f(0)示例: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.我不确定它的时间复杂度,我认为它是 O(n) 但我不确定。

Let's consider how many operations solve has to perform starting from k = 1 :让我们考虑从k = 1开始必须执行多少个操作solve

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 .所以实际上,操作的次数是1 + 2 + .. + k = (k + 1)*k/2 ~ k*k Hence, the total time complexity is O(k^2) .因此,总时间复杂度为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 .但是,如果高达k-1值已经缓存在memo并且我们需要计算f(k)那么时间复杂度是O(k)因为它只是关于总结memo[i]使得i<k

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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