ValerianBenchea

BACKTRACKING Permutari de N elemente

Sep 28th, 2021 (edited)
470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. int v[101], n;
  4. void afisare(int k)
  5. {
  6.     for(int i=1; i<=k; i++)
  7.         cout<<v[i]<<" ";
  8.     cout<<endl;
  9. }
  10. bool ebun(int k)
  11. {
  12.     for(int i=1; i<=k-1; i++)
  13.         if(v[i]==v[k])
  14.             return 0;
  15.     return 1;
  16. }
  17. void back()
  18. {
  19.     int k=1;
  20.     v[k]=0;
  21.     while(k>0)
  22.         if(v[k]<n)
  23.         {
  24.             v[k]++;
  25.             if(ebun(k))
  26.                 if(k==n)
  27.                     afisare(k);
  28.                 else
  29.                 {
  30.                     k++;
  31.                     v[k]=0;
  32.                 }
  33.         }
  34.         else
  35.             k--;
  36. }
  37. int main()
  38. {
  39.     cin>>n;
  40.     back();
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment