I am new to the forum, so I hope I am doing this right.
I am struggling with figuring out bigO complexity. Specifically time complexity. I am working on a recursive program right now that calls itself twice each recurse. Example:
compute(i,j)
edge checks
x = (compute(i-1, j) + compute(i, j-1)) /2;
return x;
I think this is O(2^n)
time, because each call produces two more. 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.
return addition of two operation from that method.
so you will get the O(n) time.
Time is O(2^(m+n))
, and space is 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. it is O(1)
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.
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.