0% found this document useful (0 votes)
10 views

Backtracking Algoritmi

The document contains C++ code for generating permutations, arrangements, and combinations of n elements taken k at a time using backtracking. It defines functions for initializing arrays, validating candidate solutions, outputting results, and implementing backtracking search. The main function calls the backtracking function to generate and output all valid permutations, arrangements, or combinations based on the problem.

Uploaded by

Andrei Stefan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Backtracking Algoritmi

The document contains C++ code for generating permutations, arrangements, and combinations of n elements taken k at a time using backtracking. It defines functions for initializing arrays, validating candidate solutions, outputting results, and implementing backtracking search. The main function calls the backtracking function to generate and output all valid permutations, arrangements, or combinations based on the problem.

Uploaded by

Andrei Stefan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Permutari de n

#include <iostream>

using namespace std;

int st[20],n;

void initializare()

cin>>n;

for (int i=0;i<20;i++) st[i]=0;

void afisare(int p)

for (int i=1;i<=p;i++)

cout<<st[i]<<' ';

cout<<endl;

int validare(int p)

int i,ok=1;

for (i=1;i<=p-1;i++)

if (st[i]==st[p]) ok=0;

return ok;

void bk(int p)
{

int i;

for (i=1;i<=n;i++)

st[p]=i;

if (validare(p))

if (p==n) afisare (p);

else bk(p+1);

int main()

initializare();

bk(1);

Aranjamente de n luate cate k

#include <iostream>

using namespace std;


int st[20] , n , k;

void initializare()

cin>>n>>k;

for (int i=0;i<20;i++) st[i]=0;

void afisare(int p)

for(int i=1;i<=p;i ++)

cout << st[i] << " ";

cout << endl;

int validare(int p)

int i,ok=1;

for(i=1;i<=p-1;i++)

if(st[i] == st[p]) ok=0;

return ok;

void bk(int p)

for(int i=1;i<=n;i++)
{

st[p] = i;

if(validare(p))

if(p==k)

afisare(p);

else

bk(p+1);

int main()

initializare();

bk(1);

return 0;

Combinari

#include <iostream>

using namespace std;

int st[20] , n , k;
void initializare()

cin>>n>>k;

for (int i=0;i<20;i++) st[i]=0;

void afisare(int p)

for(int i = 1 ; i <= p ; i ++)

cout << st[i] << " ";

cout << endl;

int validare(int p)

int i,ok=1;

for(int i = 1 ; i <= p-1 ; i++)

if(st[i] == st[p])

ok=0;

if(ok > 1)

if(st[p] <= st[p-1])

return 0;

return 1;

}
void bk(int p)

for(int i = 1 ; i <= n ; ++ i)

st[p] = i;

if(validare(k))

if(p==k)

afisare(k);

else

bk(p + 1);

int main()

cin >> n >> k;

bk(1);

return 0;

You might also like