全排列的不同方式(递归和STL算法)

#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<iomanip>
#include<functional>
#include<iterator>
#include<numeric>
#include<vector>
#include<string>
#include"windows.h"
using namespace std;
template<typename T>
void permutation(T a[], int begin_index, int end_index)
{
	if (begin_index == end_index)
	{
		copy(a, a + end_index + 1, ostream_iterator<T, char>(cout, " "));
		cout << endl;
	}	
	else
	{
		/*主要利用a[n]={a1,...,an}的全排列等于分别以a1{a2,...,an},a2{a1,a3...,an},...,
		an{a1,...,an-1}的全排列,以此类推*/
		for (int i = begin_index; i <= end_index; i++)
		{
			swap(a[begin_index], a[i]);
			permutation(a, begin_index + 1, end_index);
			swap(a[begin_index], a[i]);
		}	
	}
}
void show(const int &n)
{
	cout << n << " ";
}
int main()
{
	int num[5] = { 2, 5, 6, 1, 6 };
	permutation<int>(num, 2, 4);//全排列,不管是否有相同的成员
	cout << "Using STL:\n";
	sort(num + 2, num + 5);//首先升序排列2,5,1,6,6
	cout << "Now,the set is:";
	copy(num, num + 5, ostream_iterator<int, char>(cout, " "));
	cout << endl;
	while (next_permutation(num+2, num + 5))
	{//或者利用prev_permutation降序全排列,此时要利用sort()首先降序排列
		copy(num, num + 5, ostream_iterator<int, char>(cout, " "));
		cout << endl;
	}
	int sum = 0;
	sum=accumulate(num, num + 5, sum);
	cout << "Sum:" << sum << endl;
	int mul = 1;
	mul = accumulate(num, num + 5, mul, multiplies<int>());
	cout << "Mul:" << mul << endl;
	vector<string>str;
	str.push_back("I ");
	str.push_back("Love ");
	str.push_back("My Hometown!");
	string result = accumulate(str.begin(), str.end(), string(""));
	cout << "String:" << result << endl;
	vector<int>v(5),v1(5);
	int beginvalue = 6;
	iota(v.begin(), v.end(), beginvalue);//++
	iota(v1.begin(), v1.end(), beginvalue - 4);
	for_each(v.begin(), v.end(), show);
	cout << endl;
	cout << "The inner product of v and v1 is:" <<
		inner_product(v.begin(), v.end(), v1.begin(), beginvalue) << endl;//头文件numeric
  system("pause");
  return 0;
}

程序运行结果

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/86413068