Cho số nguyên dương N. Nhiệm vụ của bạn là hãy liệt kê tất cả các hoán vị của 1, 2, …, N theo thứ tự ngược.
Mọi người xem giúp em sai ở đâu ạ?em cám ơn nhiều
~~
#include<iostream>
using namespace std;
int n,*a,stop=0;
bool check() {
for(int i=1;i<=n;i++) {
if (a[i] != n-i+1) return false;
}
return true;
}
void swap(int &a,int &b) {
int x=a;
a=b;
b=x;
}
void next() {
int j=n-1;
while(j>0 && a[j] < a[j+1]) j--;
if (j < 0) stop=1;
else {
int k=n;
while (a[j] < a[k]) k--;
swap(a[j],a[k]);
int r;
r=j+1;
int s;
s=n;
while(r<=s) {
swap(a[r],a[s]);
r++;
s--;
}
}
}
void display() {
for(int i=n;i>=1;i--) {
cout<<a[i];
}
cout<<" ";
}
int main() {
int T;
cin>>T;
while(T--) {
cin>>n;
a=new int[n+1];
for(int i=n;i>=1;i--) {
a[i]=i;
}
display();
while(check()==false && stop==0) {
next();
display();
}
cout<<endl;
}
}
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?