是否有任何算法排列? [英] Is there any algorithm for permutations?
问题描述
我需要一个算法或伪code,用于产生排列。假如,我一直在考虑这表示字母的数量和排列的数量两个数字。我写的26英文字母的所有排列。我已经写了code,但有一个问题。现在的问题是输入3和6,我的code产生ABC,ACB,BAC,BCA, CBA,CAB 。但我需要它来生成ABC,ACB,BAC,BCA, CAB,CBA 。任何帮助将是AP preciated。在此先感谢。
#包括<的iostream>
使用名字空间std;
INT C,K,N;
无效置换(char的一个[],int i)以;
无效掉期(字符* X,字符* Y);
INT主要(无效)
{
INT吨;
所以char a [] =ABCDEFGHIJKLMNOPQRSTUVWXYZ;
CIN>>吨;
的for(int i = 1; I< = T;我++)
{
CIN>> N'GT;> K表; // N表示的字母数量和K表示的排列数
COUT<< 案例<< I&其中;&所述;:&其中;&其中; ENDL;
C = 0;
置换(一个,0);
}
返回0;
}
无效置换(字符*一,int i)以
{
如果(ⅰ== N-1)
{
为(诠释J = 0; J&所述N; J ++)
COUT<<一个[J]。
COUT<< ENDL;
C ++;
返回;
}
其他
{
对于(INT J =; J&n种放大器;和C< k; J ++)
{
交换(安培; A [1],&安培;一个[j]的);
置换(一个,1 + 1);
交换(安培; A [1],&安培;一个[j]的);
}
}
返回;
}
无效掉期(字符* X,字符* Y)
{
焦温度;
TEMP = * X;
* X = * Y;
* Y =温度;
返回;
}
看的std :: next_permutation
功能
I need an algorithm or pseudo code for generating permutations. Suppose, I have been given two numbers which denote the number of letters and the number of permutations. I have to write all the permutations from the 26 ENGLISH letter. I have written a code but there is a problem. The problem is for input 3 and 6, my code generates ABC, ACB, BAC, BCA, CBA, CAB. But i need it to generate ABC, ACB, BAC, BCA, CAB, CBA. Any help would be appreciated. Thanks in Advance.
#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;
}
Look at std::next_permutation
function
这篇关于是否有任何算法排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!