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 studied complexity from some website where I came across this code. In my understanding, the next line is repeated N times. Thus, the complexity is O (N).
for (int first=0; first<N; first++)
Next, I look at a recursive call.
for (int next=0; next<N; next++) if (!used[next]) try(which+1, next);
Thus, this recursive call has a number of steps: t (n) = Nc + t (0) (where is some constant step) There we can say that for this step the complexity is = O (N).
So the overall complexity is O (NN) = O (N ^ 2)
As far as I understand? Thank you
source share