递归5: 生成置换的递归与STL算法实现

#include <iostream>
#include <string>
#include <algorithm>	// sort()、next_permutation()
using namespace std;
// (递归算法 -- 生成置换)(开发困难)
// worstTime(n) 是 O(n!)
void rec_permute(string s, unsigned k)
{
	if (k == s.length() -1)
		cout << s << "	";
	else
		for (unsigned i = k; i < s.length(); i++)
		{
			swap(s[i], s[k]);
			rec_permute(s, k+1);
		}
}

void permute(const string& s)
{
	rec_permute(s, 0);
}

// (STL的通用算法 -- 生成置换)
void permutecopy(string s)
{
	// 使用通用型算法 next_permutation()前必须保证有序性
	sort(s.begin(), s.end());
	cout << s << "	";
	while (next_permutation(s.begin(), s.end()))
		cout << s << "	";
}

int main()
{
	string s = "ABC";
	cout << "permute():\n";
	permute(s);
	cout << endl << endl;

	cout << "permutecopy():\n";
	permutecopy(s);
	cout << endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值