最长路径算法与递归方法的计算复杂度

编程入门 行业动态 更新时间:2024-10-14 16:24:12
本文介绍了最长路径算法与递归方法的计算复杂度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我写了一个代码段来确定图中的最长路径.以下是代码.但是由于中间有递归方法,我不知道如何获得计算复杂性.由于找到最长的路径是一个NP完整问题,因此我假设它类似于O(n!)或O(2^n),但是我该如何确定呢?

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 recursive method in the middle. Since finding the longest path is an NP complete problem I assume it's something like O(n!) or O(2^n), but how can I actually determine it?

public static int longestPath(int A) { int k; int dist2=0; int max=0; visited[A] = true; for (k = 1; k <= V; ++k) { if(!visited[k]){ dist2= length[A][k]+longestPath(k); if(dist2>max){ max=dist2; } } } visited[A]=false; return(max); }

推荐答案

您的重复关系为T(n, m) = mT(n, m-1) + O(n),其中n表示节点数,而m表示未访问节点数(因为您调用longestPath m次,并且有一个循环执行访问的测试n次).基本情况是T(n, 0) = O(n)(只是访问过的测试).

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).

解决这个问题,我相信您得到的T(n,n)是O(n * n!).

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

编辑

工作:

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 oeis/A000522) = O(n*n!)

更多推荐

最长路径算法与递归方法的计算复杂度

本文发布于:2023-11-30 17:27:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650892.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   复杂度   算法   路径   最长

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!