What will be the complexity of this code?

时间:2015-07-31 20:52:35

标签: algorithm recursion big-o time-complexity complexity-theory

My code is :

vector<int> permutation(N); 
vector<int> used(N,0);

void try(int which, int what) {
  // try taking the number "what" as the "which"-th element
  permutation[which] = what;
  used[what] = 1;

  if (which == N-1)
    outputPermutation();
  else
   // try all possibilities for the next element
  for (int next=0; next<N; next++)
    if (!used[next])
    try(which+1, next);

  used[what] = 0;
} 

int main() {
  // try all possibilities for the first element
  for (int first=0; first<N; first++)
    try(0,first);
}

I was learning complexity from some website where I came across this code. As per my understanding, the following line iterates N times. So the complexity is O(N).

for (int first=0; first<N; first++)

Next I am considering the recursive call.

for (int next=0; next<N; next++)
   if (!used[next])
    try(which+1, next);

So, this recursive call has number of step involved = t(n) = N.c + t(0).(where is some constant step) There we can say that for this step, the complexity is = O(N).

Thus the total complexity is - O(N.N) = O(N^2)

Is my understanding right? Thanks!

2 个答案:

答案 0 :(得分:3)

这个算法的复杂性是O(N!)(如果outputPermutation取O(N)似乎是可能的话,甚至是O(N!* N)。

该算法输出0..N自然数的所有排列而不重复。

递归函数try本身依次尝试将N个元素放入位置which,并且对于每次尝试,它递归调用自己的下一个which位置,直到which达到N -1。此外,对于每次迭代,try实际上被调用(N - which)次,因为在每个级别上,一些元素被标记为used以消除重复。因此该算法采用N *(N-1)*(N-2)... 1步。

答案 1 :(得分:0)

这是一个递归函数。功能&#34;尝试&#34;递归调用自身,因此main()中有一个循环,try()中有一个循环,try()的递归调用循环,try()的下一个递归调用中的循环等等。

您需要非常仔细地分析此功能的作用,否则您将得到完全错误的结果(就像您所做的那样)。您可能会考虑实际运行此代码,其值为N = 1到20并测量时间。你会发现它绝对不是O(N ^ 2)。实际上,不要跳过N的任何值;你会明白为什么。