我无法找到回溯的时间复杂性-旅行商问题。由于回溯-旅行推销员问题使用了汉密尔顿周期的时间复杂度,因此我尝试进行搜索,这些是我发现的:
我从阿卜杜勒·巴里(Abdul Bari)的youtube频道中看到,回溯-哈密顿循环的时间复杂度为n ^ n,而stackoverflow中一个问题的答案是:n!
n ^ n参考:https://www.youtube.com/watch?v=dQr4wZCiJJ4&t=389s
n!参考:How to calculate time complexity of backtracking algorithm?
我真的不知道如何计算时间复杂度,你们能帮我从这个确定时间复杂度吗(这是回溯-旅行商问题代码):
参考:https://www.geeksforgeeks.org/travelling-salesman-problem-implementation-using-backtracking/
public class GFG{
// Function to find the minimum weight
// Hamiltonian Cycle
static int tsp(int[][] graph, boolean[] v,
int currPos, int n,
int count, int cost, int ans)
{
// If last node is reached and it has a link
// to the starting node i.e the source then
// keep the minimum value out of the total cost
// of traversal and "ans"
// Finally return to check for more possible values
if (count == n && graph[currPos][0] > 0)
{
ans = Math.min(ans, cost + graph[currPos][0]);
return ans;
}
// BACKTRACKING STEP
// Loop to traverse the adjacency list
// of currPos node and increasing the count
// by 1 and cost by graph[currPos,i] value
for (int i = 0; i < n; i++)
{
if (v[i] == false && graph[currPos][i] > 0)
{
// Mark as visited
v[i] = true;
ans = tsp(graph, v, i, n, count + 1,
cost + graph[currPos][i], ans);
// Mark ith node as unvisited
v[i] = false;
}
}
return ans;
}
// Driver code
public static void main(String[] args)
{
// n is the number of nodes i.e. V
int n = 4;
int[][] graph = {{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}};
// Boolean array to check if a node
// has been visited or not
boolean[] v = new boolean[n];
// Mark 0th node as visited
v[0] = true;
int ans = Integer.MAX_VALUE;
// Find the minimum weight Hamiltonian Cycle
ans = tsp(graph, v, 0, n, 1, 0, ans);
// ans is the minimum weight Hamiltonian Cycle
System.out.println(ans);
}
}
// This code is contributed by Rajput-Ji
答案 0 :(得分:1)
首先,n! = O(n^n)
可以由n!= n* (n-1) *(n-2) ....
证明
n^n = n * n * n....
显然n!
受n^n
的限制,因此您发现“哈密顿循环为n^n
,而stackoverflow中一个问题的答案为n!
” < / p>
对于TSP回溯,在最坏的情况下,您需要进行(n-1)!
排列,每个人都必须做n-1
附加才能找到成本。所以(n-1) * (n-1)!
-> O(n!)