字符串排列组合

1.输入字符串abc,输出abc acb bac bca cab cba,代码如下:

#include<algorithm>
#include<string>
#include<vector>
#include<iostream>
using namespace std;

void backTrack(string str, vector<string> &res, int k) {
	if (str.size() == k) {
		res.push_back(str);
		return;
	}
	for (int i = k; i<str.size(); i++) {
		swap(str[i], str[k]);
		backTrack(str, res, k + 1);
		swap(str[i], str[k]);
	}
}
int main() {
	string str = "abc";
	vector<string> res;
	backTrack(str, res,0);
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << endl;
	}
}

2.输入字符串abcc,即存在重复字符,输出abcc accb bacc bcca cab ccba ...代码如下:

#include<algorithm>
#include<string>
#include<vector>
#include<iostream>
#include<unordered_map>
using namespace std;

void backTrack(string str,vector<string> &res,int k) {
	if (str.size() == k) {
		res.push_back(str);
		return;
	}
	unordered_map<char, int> m;
	for (int i = k; i < str.size(); i++) {
		if (m[str[i]]==0) {
			m[str[i]] = 1;
			swap(str[i], str[k]);
			backTrack(str, res, k + 1);
			swap(str[i], str[k]);
		}
	}
}

int main() {
	string str = "abcc";
	vector<string> res;
	backTrack(str,res,0);
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << endl;
	}
}

3.输入字符串abc,输出aaa aab aac baa caa ...,代码如下:

#include<algorithm>
#include<string>
#include<vector>
#include<iostream>
using namespace std;

void backTrack(string str, vector<string> &res,string perRes, int k) {
	if (str.size() == k) {
		res.push_back(perRes);
		return;
	}
	for (int i = 0; i<str.size(); i++) {
		perRes += str[i];
		backTrack(str, res, perRes, k + 1);
		perRes.erase(perRes.end()-1);
	}
}
int main() {
	string str = "abc";
	vector<string> res;
	string perRes;
	backTrack(str, res, perRes,0);
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << endl;
	}
}

4.输入字符串abc,输出a,b,c,ab,ac,bc,abc,代码如下:

#include<algorithm>
#include<string>
#include<vector>
#include<iostream>
using namespace std;

void strCombine(string str,vector<string> &res,string perRes) {
	if (str.size() == 0) {
		if (perRes.size() != 0) {
			res.push_back(perRes);
		}
		return;
	}
	strCombine(&str[1], res, perRes);
	perRes += str[0];
	strCombine(&str[1], res, perRes);
}

int main() {
	string str = "abc";
	vector<string> res;
	string perRes;
	strCombine(str,res,perRes);
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << endl;
	}
}












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值