我需要一种算法或伪代码来生成排列。假设,我得到了两个数字,分别表示字母的数量和排列的数量。
我必须写出 26 个英文字母的所有排列。我已经写了一个代码,但是有一个问题。问题在于输入 3 和 6,我的代码生成 ABC, ACB, BAC, BCA, CBA, CAB。但我需要它来生成 ABC, ACB, BAC, BCA, CAB, CBA。
#include<iostream>
using namespace std;
int c, K, N;
void permute(char a[], int i);
void swap(char* x, char* y);
int main(void)
{
int t;
char a[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cin >> t;
for(int i=1; i<=t; i++)
{
cin >> N >> K;//N denotes number of letters and K denotes number of permutations
cout << "Case " << i <<":" << endl;
c=0;
permute(a,0);
}
return 0;
}
void permute(char* a, int i)
{
if(i==N-1)
{
for(int j=0; j<N; j++)
cout << a[j];
cout << endl;
c++;
return;
}
else
{
for(int j=i; j<N && c<K; j++)
{
swap(&a[i],&a[j]);
permute(a,i+1);
swap(&a[i],&a[j]);
}
}
return;
}
void swap(char* x, char* y)
{
char temp;
temp=*x;
*x=*y;
*y=temp;
return;
}