简体   繁体   English

这种特定方法的时间复杂度是多少?

[英]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. moveToptoO(1) ,因此不应影响运行时。

That depends on the time complexity of the moveTopto and buffer.moveTopto . 这取决于moveToptobuffer.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.

相关问题 这种方法的时间复杂度和辅助空间是多少? - what's the Time Complexity and Auxiliary space for this method? NavigableMap的floorEntry()方法的时间复杂度是多少? - What is the time complexity of floorEntry() method of NavigableMap? Java StringBuilder.substring()方法的时间复杂度是多少? 如果它是线性的,是否有一个恒定的时间复杂度方法来获得子串? - What is the time complexity of Java StringBuilder.substring() method? If it is linear, is there a constant time complexity method to get a substring? 方法的时间复杂度 - Time complexity of the method 以下方法的时间复杂度 - Time complexity of the following method 查找此方法的时间复杂度 - Finding the time complexity of this method 在Java中使用HashSets时,方法retainAll的时间和空间复杂度是多少? - What is the time and space complexity of method retainAll when used on HashSets in Java? String 类的 Java hashCode 方法的时间复杂度是多少? - What is the time complexity of Java hashCode method for the String class? java.util.Collections.sort() 方法的时间复杂度是多少? - What is the time complexity of java.util.Collections.sort() method? java.util.HashMap 类的 keySet() 方法的时间复杂度是多少? - What is the time complexity of java.util.HashMap class' keySet() method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM