我需要一个算法或伪代码来生成排列。假设,我已经给出了两个数字,表示字母的数量和排列的数量。我必须写下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;
}
你google一下呢? – Marcin 2012-07-20 19:32:22
结果顺序是否重要? – 2012-07-20 20:10:33
是的,订单很重要。 – 2012-07-21 15:03:04