我需要一個算法或僞代碼來生成排列。假設,我已經給出了兩個數字,表示字母的數量和排列的數量。我必須寫下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