[英]How to find recursive relation of this recursive function?
Here I got a function like this and I want to find the recursive relation of that and after that calculate time complexity of that recursive relation.在这里,我得到了一个这样的函数,我想找到它的递归关系,然后计算该递归关系的时间复杂度。
public static void f(int n) {
if (n == 1) {
//" Do sth "
} else {
for (int i = 1; i < n; i++) {
f(i - 1);
//" Do sth "
}
}
}
actually I tried a lot for that and I got T(n) = n * f( n-1) for this function as the relation but I am not sure about that .实际上我为此尝试了很多,我得到了这个函数的T(n) = n * f( n-1)作为关系,但我不确定。 could you help me find the correct relation and solve it ?你能帮我找到正确的关系并解决它吗?
Assuming T(1) = "Do sth" is constant work ie it doesn't depend on the input size n
, you could write the recursive time function as :假设 T(1) = "Do sth" 是恒定的工作,即它不依赖于输入大小n
,您可以将递归时间函数编写为:
T(n) = T(1) + T(2) + ... + T(n-1)
= { T(1) } + { T(1) } + { T(1) + T(2) } + { T(1) + T(2) + T(3) } + { T(1) + T(2) + T(3) + T(4) } +....
[let T(1) = x]
= x + x + {x + x} + {x + x + (x + x)} + {x + x + (x + x) + x + x + (x + x)} +....
= x + x + 2x + 4x + 8x + ...
~ x.2^(n-2)
~ O(2^n)
Here is a python program to demonstrate the sequence of coefficients for the summation:这是一个python程序,用于演示求和的系数序列:
t = [0 for i in range(10)]
for i in range(1,10):
if i == 1:
t[i] = 1
else:
val = 0
for j in range(1,i):
val += t[j]
t[i] = val
print(t[1:])
prints : [1, 1, 2, 4, 8, 16, 32, 64, 128]打印 : [1, 1, 2, 4, 8, 16, 32, 64, 128]
You can see that 2 (n-2) for n >= 2 holds good at each 'n' and complexity is O(2 n )你可以看到 2 (n-2) for n >= 2 在每个 'n' 上都很好,复杂度是 O(2 n )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.