[英]Time complexity of recursive algorithm
I have a grid with x -sided field in it. 我有一个带有x边字段的网格。 Every field contains a link to it's x surrounding fields. 每个字段都包含一个指向x个周围字段的链接。 [ x is constant ] [ x是常数 ]
I have an algorithm which is implemented in this field, (which can probably be optimized): 我有一个在此领域中实现的算法(可能可以对其进行优化):
[java like pseudocode] [类似于伪代码的Java]
public ArrayList getAllFields(ArrayList list) {
list.addToList(this);
for each side {
if ( ! list.contains(neighbour) && constantTimeConditionsAreMet()) {
neighbour.getAllFields(list) //Recursive call
}
}
return list;
}
I'm having trouble finding the time complexity. 我很难找到时间的复杂性。
ArrayList#contains(Object)
runs in linear time ArrayList#contains(Object)
在线性时间内运行 How do i find the time complexity? 如何找到时间复杂度? My approach is this: 我的方法是这样的:
T(n) = O(1) + T(n-1) +
c(nbOfFieldsInArray - n) [The time to check the ever filling ArrayList]
T(n) = O(1) + T(n-1) + c*nbOfFieldsInArray - cn
Does this give me T(n) = T(n-1) + O(n)
? 这会给我T(n) = T(n-1) + O(n)
吗?
The comment you added to your code is not helpful. 您添加到代码中的注释没有帮助。 What does getContinent
do? getContinent
什么作用?
In any case, since you're using a linear search ( ArrayList.contains
) for every potential addition to the list, then it looks like the complexity will be Omega(n^2). 无论如何,由于对列表中的每个潜在加法都使用了线性搜索( ArrayList.contains
),因此看起来复杂度将为Omega(n ^ 2)。
You recurrence seems correct T(n) = T(n-1) + theta(1)
. 您的复发似乎是正确的T(n) = T(n-1) + theta(1)
。
If you draw the recursion tree you'll notice you have a single branch with the values theta(n-1), theta(n-2), ..., theta(2), theta(1)
, if you add up all the levels you get the arithmetic series 1+2+3+...+n 如果您绘制递归树,您会发现您有一个分支,值分别为theta(n-1), theta(n-2), ..., theta(2), theta(1)
获得算术级数1 + 2 + 3 + ... + n的所有级别
S1 = 1+2+3+...+n
If you define 如果您定义
S2 = n+...+3+2+1
and then calculate S1+S2
you get 然后计算出S1+S2
S1 + S2 = 2*S1 = (n+1) + (n+1) + ... + (n+1) = n(n+1)
therefore 因此
2*S1 = n(n-1) => S1 = n(n-1)/2
which means T(n) = 1/2 theta(n(n-1)) = 1/2 theta(n^2) = theta(n^2)
这意味着T(n) = 1/2 theta(n(n-1)) = 1/2 theta(n^2) = theta(n^2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.