字符排列组合

排列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;
}

猜你喜欢

转载自blog.csdn.net/weixin_40804971/article/details/82781497