O(n)的
for (int i=0;i<n;i++)
编辑后:我最后的答案是
for(int i =(n - 1); i > 1; i--)
{
factorial = factorial * i;
}
for (int j=n-2;j<factorial;j++)
{
}
O(n)的
for (int i=0;i<n;i++)
编辑后:我最后的答案是
for(int i =(n - 1); i > 1; i--)
{
factorial = factorial * i;
}
for (int j=n-2;j<factorial;j++)
{
}
fact = 1;
for(c = 1 ; c <= n ; c++)
{
fact = fact*c;
}
这样吗?
如果我们在同一页上这里...我认为这看起来像..
Tau(fetch) + Tau(store) + (2Tau(fetch) + Tau(<))*(N + 1) + (2Tau(fetch) + Tau(+) + Tau(store)) * N
最简单的答案是 的for(int i = 0;我<阶乘(N);在实践中,通常O(n!)算法是通过尝试列表的所有不同排列而工作的算法,也就是说,您可以对列表重新排序的所有不同方式。一个例子是找到通过地图中所有点的最短线,称为旅行推销员问题。你需要尝试所有不同的方式来完成所有的要点,那就是O(n!)。
IEnumerable<List<int>> nextPermutation(List<int> nodesLeft)
{
if (nodesLeft.Count == 0)
{
yield return new List<int>();
}
else
{
for (int i = 0; i < nodesLeft.Count; i++)
{
List<int> newNodesLeft = new List<int>(nodesLeft);
newNodesLeft.removeAt(i);
foreach (List<int> subPermutation in nextPermutation(newNodesLeft)
{
subPermutation.add(nodesLeft[i]);
yield return subPermutation;
}
}
}
}
void main()
{
foreach (List<int> permutation in nextPermutation(new List<int>(new int[]{1,2,3,4,5}))) {
//every permutation of [1,2,3,4,5] will be generated here
//this will take O(n!) to complete, where n is the number of nodes given (5 in this case)
}
}
谢谢!我的代码根据您的建议而改变! – 2012-02-05 08:48:31
没问题。如果你还没有,请不要忘记点击旁边的好标志。 – mtanti 2012-02-05 10:12:33
如果递归被允许,那么:
void loop(int n)
{
if(n == 1)
return; // the program gets here exactly n! times
for(int i=0; i<n; i++)
loop(n-1);
}
没有在for循环中的任何声明....只是使用嵌套的for循环.. – 2012-02-05 06:32:26