编写一个简短的C++程序,输出所有可能的字符串,这些字符串是通过将每个字符“a”、“b”、“C”、“d”、“e”和“f”
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
的实现及其工作原理。
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度