![](/img/trans.png)
[英]program that outputs the different characters (not the ones in common) between 2 strings that read all characters in c++
[英]Write a short C++ program that outputs all possible strings formed by using each of the characters ’a’, ’b’, ’c’, ’d’, ’e’, and ’f’ exactly once
我遇到了这个问题,但无法解决。 我所能编码的只是像ab,ac,ad,ae,af之类的小字符串。 但不适用于较长的字符串,例如abc,abcd等 。 如果有人可以引导我寻求某种解决方案,那将是非常不错的。 我希望没有递归,但如果没有,那么递归也可以。
这是我的代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<string> make_string(vector<char>vec, char ch)
{
int i=0;
vec.erase(remove(vec.begin(), vec.end(), ch), vec.end());
int size = vec.size();
vector<string>all_strings;
string answer="";
for(i=0;i<size;i++) //here is the "meat". I could add a few more for loops for longer strings
// But I think that would just get messy.
{
answer= answer+ch+vec[i];
all_strings.push_back(answer);
answer="";
}
return all_strings;
}
void print_vector(vector<string>vec)
{
int i=0;
int size = vec.size();
for(i=0;i<size;i++)
{
cout<<vec[i]<<endl;
}
cout<<"--------------------------";
cout<<endl;
}
int main()
{
vector<char>vec;
vec.push_back('a');
vec.push_back('b');
vec.push_back('c');
vec.push_back('d');
vec.push_back('e');
vec.push_back('f');
int i=0;
vector<string>my_strings;
int size=vec.size();
for(i=0;i<size;i++)
{
my_strings=make_string(vec,vec[i]);
print_vector(my_strings);
my_strings.clear();
}
return 0;
}
您正在寻找一种置换算法。 请在wordaligned.org上查看此帖子,该帖子描述了该问题的迭代解决方案:
作者的代码非常简单,并使用了标准库:
#include <algorithm>
#include <cstdio>
int main()
{
char xs[] = "abcdef"; // <-- modified to fit the question.
do
{
std::puts(xs);
}
while (std::next_permutation(xs, xs + sizeof(xs) - 1));
return 0;
}
如果您进一步阅读,将讨论next_permutation
的实现及其工作方式的细分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.