tungggg

Sinh to hop backtrack

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