[英]What is the time complexity of this particular method?
class Tower {
public void moveDisks(int n, Tower Destination, Tower Buffer) {
if (n > 0) {
moveDisks(n-1, Buffer, Destination);
moveTopto(Destination);
Buffer.moveDisks(n-1, Destination, this);
}
}
}
Here is the code to the method I mentioned above. 这是我上面提到的方法的代码。 This is part of an algorithm that solves the classic Hanoi Tower problem.
这是解决经典河内塔问题的算法的一部分。 I just can't wrap my head around a time complexity for this as the it has quite a bit of recursion.
我只是无法解决这个问题,因为它有很多递归。
This is a method within the class Tower
. 这是
Tower
类中的一种方法。 moveTopto
is O(1)
, so shouldn't affect the runtime. moveTopto
是O(1)
,因此不应影响运行时。
That depends on the time complexity of the moveTopto
and buffer.moveTopto
. 这取决于
moveTopto
和buffer.moveTopto
的时间复杂度。
Basically to compute the complexity you will have to add the up the times. 基本上,要计算复杂度,您必须加总时间。 The time for
n
will be the time for n-1
, plus the time for moveTopto
plus the time for buffer.moveTopto
plus a constant. 其时
n
将是时间n-1
,加上用于时间moveTopto
加上时间buffer.moveTopto
加上常数。 Now you see that it will have at least O(N)
, but can have higher, especially if buffer.moveTopto
have non-constant time complexity. 现在,您将看到它至少具有
O(N)
,但可以更高,尤其是在buffer.moveTopto
具有非恒定时间复杂度的情况下。
If you mean Buffer.moveTopto
then the time would be about twice the time for n-1
, that is you would have t(n) = 2*t(n-1)+constant
. 如果您的意思是
Buffer.moveTopto
那么该时间将是n-1
两倍,即t(n) = 2*t(n-1)+constant
。 That gives O(2^n)
. 得出
O(2^n)
。
Good explanation of recursive algorithms complexity analysis Video Tutorial 递归算法复杂性分析的很好解释视频教程
PS. PS。 If you're too lazy to open the link and understand and just want the answer - complexity ~ O(2 ^ n)
如果您懒得打开链接并理解并只想答案-复杂度〜O(2 ^ n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.