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