编写一个简短的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

本文关键字:字符串 字符 一个 C++ 有可能 程序 输出      更新时间:2023-10-16

我遇到了这个问题,但我无法解决它。我所能编码的只是小字符串,如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的实现及其工作原理。