Il mio codice è:Quale sarà la complessità di questo codice?
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);
}
stavo imparando la complessità da qualche sito web in cui mi sono imbattuto in questo codice. Secondo la mia comprensione, la riga seguente fa scorrere N volte. Quindi la complessità è O (N).
for (int first=0; first<N; first++)
Avanti Sto considerando la chiamata ricorsiva.
for (int next=0; next<N; next++)
if (!used[next])
try(which+1, next);
Così, questa chiamata ricorsiva è il numero di step coinvolti = T (n) = Nc + t (0). (Dove è un certo passo costante) Non possiamo dire che per questo passo, la complessità è = O (N).
Così la complessità totale è - O (N.N) = O (N^2)
è la mia comprensione giusto? Grazie!
Grazie mille! Risposta perfetta! –