全排列的不同方式(递归和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;
}

程序运行结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值