字符排列组合

排列A(n,n)

#include <iostream>
#include<string>
#include <vector>

using namespace std;

/* begin为开始的位置0 */
/* res存放所有的排列方式 */

void permutation(string& str_orgin, int begin, vector<string>& res){
	if(begin == str_orgin.size() - 1){
		res.push_back(str_orgin);
		return;
	}

	for(int i = begin; i < str_orgin.size(); ++i){
		//如果有重复的字符就返回
		if(i != begin && str[i] == str[begin])
			continue;
		swap(str_orgin[begin], str_orgin[i]);
		permutation(str_orgin, begin + 1, res);
		swap(str_orgin[begin], str_orgin[i]);
	}
}

int main(){
	string str_orgin = "abc";
	vector<string> res;
	permutation(str_orgin, 0, res);
	for(auto s : res)
		cout<<s<<endl;
    cout<<res.size()<<endl;

	return 0;
}

组合C(n,m)

#include <iostream>
#include<string>
#include <vector>

using namespace std;

/* 从str_orgin 中选择m个字符 */
/* begin为开始的位置0,str_combined存储一种组合方式 */
/* res存放所有的组合方式 */

void combination(string& str_orgin, int m, int begin,string& str_combined, vector<string>& res){
	if(begin == str_orgin.size() && m != 0)
		return;
	if(m == 0){
		res.push_back(str_combined);
		return;
	}
	str_combined.push_back(str_orgin[begin]);//选择该字符
	combination(str_orgin, m - 1, begin + 1, str_combined, res);
	str_combined.pop_back();//不选该字符
	combination(str_orgin, m, begin + 1, str_combined, res);
}

int main(){
	string str_orgin = "abcde";
	string str_combined;
	vector<string> res;
	combination(str_orgin, 3, 0, str_combined, res);
	for(auto s : res)
		cout<<s<<endl;

	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值