简体   繁体   English

复杂性,时间和空间

[英]Complexity, both time and space

I am new to the forum, so I hope I am doing this right. 我是论坛的新手,所以我希望我做得对。

I am struggling with figuring out bigO complexity. 我正在努力搞清楚bigO的复杂性。 Specifically time complexity. 特别是时间复杂。 I am working on a recursive program right now that calls itself twice each recurse. 我正在研究一个递归程序,每次递归调用自己两次。 Example: 例:

compute(i,j) 计算(I,J)

edge checks 边缘检查

x = (compute(i-1, j) + compute(i, j-1)) /2; x =(compute(i-1,j)+ compute(i,j-1))/ 2;

return x; 返回x;

I think this is O(2^n) time, because each call produces two more. 我认为这是O(2^n)时间,因为每个调用产生两个以上。 Is this correct? 这个对吗? Is it the same for complexity? 复杂性是否相同?

I suggest you to use array of int or var-args like compute(int... val) send 4 argument 2 for first operation last 2 for second operation your performing inside this method. 我建议你使用int或var-args数组,比如compute(int ... val)发送4参数2进行第一次操作,最后2次进行第二次操作你在这个方法中执行。

return addition of two operation from that method. 从该方法返回两个操作的添加。

so you will get the O(n) time. 所以你会得到O(n)时间。

Time is O(2^(m+n)) , and space is O(1) . 时间是O(2^(m+n)) ,空间是O(1)

For Time complexity: 对于时间复杂性:

  • O(m,1) = O(m-1, 1) + O(1,1) = O(m-2,1) + 2O(1,1) = ... = O(m)
  • O(m,2) = O(m,1) + O(m-1,2) = O(m) + O(m-1, 1) + O(m-2,2) = ... = O(m) + O(m-1) + ... + O(1) + O(1,2) = O(m^2)
  • O(m,3) = O(m,2) + O(m-1,3) = O(m^2) + O(m-1, 2) + O(m-2,3) = ... = O(m^2) + - O((m-1)^2) + ... + O(1^2) + O(1,3) = O(2^m)
  • O(m,4) = O(m,3) + O(m-1,4) = O(2^m) + O(m-1, 3) + O(m-3,4) = ... = O(2^m) + O(2^(m-1)) + ... + O(2^1) + O(1,4) = O(2^(m+1))
  • O(m,5) = O(m,4) + O(m-1,5) = O(2^(m+1)) + O(m-1, 4) + O(m-3,5) = ... = O(2^(m+1)) + O(2^(m)) + ... + O(2^3) + O(1,5) = O(2^(m+2))
  • ... ...
  • O(m,n) = O(2^(m+n))

For Space complexity: 对于空间复杂性:

it does not use ex space. 它不使用ex空间。 it is O(1) O(1)

PS PS

optimize 优化

def compute(i,j):
    result = [[0 for x in range(i)] for y in range(j)]
    for x in rangex(i):
        for y in xrange(j):
            if x == 0 or y == 0:
                result[x][y] = value(x,y); // compute(i,j) and (i,j) is edge
            else:
                result[x][y] = (result[x][y-1] + result[x-1][y]) / 2
    return result[i-1][j-1]

This is O(m*n) time, and O(m*n) space. 这是O(m*n)时间和O(m*n)空间。

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

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