Computational complexity of a longest path algorithm witn a recursive method

前端 未结 1 326
我寻月下人不归
我寻月下人不归 2021-01-12 21:16

I wrote a code segment to determine the longest path in a graph. Following is the code. But I don\'t know how to get the computational complexity in it because of the recurs

相关标签:
1条回答
  • 2021-01-12 21:39

    Your recurrence relation is T(n, m) = mT(n, m-1) + O(n), where n denotes number of nodes and m denotes number of unvisited nodes (because you call longestPath m times, and there is a loop which executes the visited test n times). The base case is T(n, 0) = O(n) (just the visited test).

    Solve this and I believe you get T(n, n) is O(n * n!).

    EDIT

    Working:

    T(n, n) = nT(n, n-1) + O(n) 
            = n((n-1)T(n, n-2) + O(n)) + O(n) = ...
            = n(n-1)...1T(n, 0) + O(n)(1 + n + n(n-1) + ... + n(n-1)...2)
            = O(n)(1 + n + n(n-1) + ... + n!)
            = O(n)O(n!) (see http://oeis.org/A000522)
            = O(n*n!)
    
    0 讨论(0)
提交回复
热议问题