Example of Big O of 2^n

后端 未结 7 570
情歌与酒
情歌与酒 2021-01-31 09:11

So I can picture what an algorithm is that has a complexity of n^c, just the number of nested for loops.

for (var i = 0; i < dataset.len; i++ {
    for (var         


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 10:03

      int Fibonacci(int number)
     {
      if (number <= 1) return number;
    
      return Fibonacci(number - 2) + Fibonacci(number - 1);
     }
    

    Growth doubles with each additon to the input data set. The growth curve of an O(2N) function is exponential - starting off very shallow, then rising meteorically. My example of big O(2^n), but much better is this:

    public void solve(int n, String start, String auxiliary, String end) {
       if (n == 1) {
           System.out.println(start + " -> " + end);
       } else {
           solve(n - 1, start, end, auxiliary);
           System.out.println(start + " -> " + end);
           solve(n - 1, auxiliary, start, end);
       }
    

    In this method program prints all moves to solve "Tower of Hanoi" problem. Both examples are using recursive to solve problem and had big O(2^n) running time.

提交回复
热议问题