33,008
社区成员
发帖
与我相关
我的任务
分享
// PermutationAndCombination.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
using namespace std;
//----------------此处只对字符和数字进行排列组合---------------------
typedef vector<char> CHAR_ELEMENTS;
CHAR_ELEMENTS CharElements;
typedef vector<float> FLOAT_ELEMENTS;
FLOAT_ELEMENTS FloatElements;
typedef vector<string> STR_ELEMENTS;
STR_ELEMENTS StrElements;
int ElemNum = 1; //仅仅用于输出元素序号
//-------------------可以获取多个类型的元素-------------------
template<class T>
void GetElements(vector<T> &Elems)
{
int counts = 0;
T elem;
cout<<"请输入元素个数"<<endl;
cin>>counts;
for ( int i = 0; i< counts; i ++ )
{
cout<<"请输入第"<<i<<"号元素: ";
cin>>elem;
Elems.push_back(elem);
}
}
template<class T>
void Swap(T &a1,T &a2)
{
T temp = a1;
a1 = a2;
a2 = temp;
}
// PerOrCom:
// true:排列
// false:组合
template<class T>
void PrintResult(vector<T> &Elems,bool PerOrCom)
{
if ( PerOrCom )
{
cout<<"第"<<ElemNum++<<"种排列: ";
}
else
{
cout<<"第"<<ElemNum++<<"种组合: ";
}
int size = Elems.size();
for (int i = 0; i< size ; i ++ )
{
cout<<Elems[i]<<' ';
}
cout<<endl;
}
template<class T>
void Perm(vector<T> &Elems,int e)
{
int size = Elems.size();
if ( e >= size - 1 )
{
PrintResult(Elems,true); //已经完成排列就打印出来
return ;
}
for ( int i = e; i < size; i ++ )
{
//构造新的元素组合用于排序
vector<T> NewElems(Elems);
Swap( NewElems[e], NewElems[i] );
Perm(NewElems,e + 1); //递归求排列
}
}
template<class T>
void Permutation(vector<T> &Elems)
{
Perm(Elems,0);
ElemNum = 1;
cout<<"------------------------------"<<endl;
}
template<class T>
void Comb(vector<T> &Elems,vector<T> & ret,int e)
{
int size = Elems.size();
if( e > size - 1 )
{
PrintResult(ret,false);
return;
}
for ( int i = 0 ; i < size; i ++ )
{
ret[e] = Elems[i];
Comb(Elems,ret,e + 1);
}
}
template<class T>
void Combination(vector<T> &Elem)
{
vector<T> ret(Elem);
Comb(Elem,ret,0);
ElemNum = 1;
cout<<"---------------------------"<<endl;
}
//====================================================
int _tmain(int argc, _TCHAR* argv[])
{
cout <<"请输入需要排列的元素(不重复):"<<endl;
GetElements(CharElements);
Permutation(CharElements);
Combination(CharElements);
system("pause");
return 0;
}
static void 交换数据<T>(ref T 数据1, ref T 数据2)
{
T 调度;
调度 = 数据1;
数据1 = 数据2;
数据2 = 调度;
}
static string[] 翻换(string 字符串, int 量, int 起位)
{
string[] 输出 = new string[量 * (量 - 1)];
char[] 字符串组 = 字符串.ToCharArray();
int 数 = 0;
do
{
int 读 = (起位 + 数) % 量;
char a = 字符串组[读], b = 字符串组[(读 + 1) % 量];
交换数据(ref a, ref b);
字符串组[读] = a;
字符串组[(读 + 1) % 量] = b;
输出[数] = string.Join("", 字符串组);
} while (++数 < 量 * (量 - 1));
return 输出;
}
string aaa = "12345"; List<string> CCC = new List<string>(), EEE = new List<string>();
int bbb = 0;
do
{
CCC.AddRange(翻换(aaa, aaa.Length, bbb));
} while (++bbb < aaa.Length);
Console.WriteLine(string.Join(" ", CCC.Distinct().OrderBy(a => a)));
foreach (string dd in CCC.Distinct()) EEE.AddRange(翻换(dd, dd.Length, 0));
Console.WriteLine(string.Join(" ", EEE.Distinct().OrderBy(a => a)));