📜  使用STL对给定的字符串进行排列

📅  最后修改于: 2021-04-25 00:03:13             🧑  作者: Mango

排列(也称为“排列编号”或“顺序”)是将有序列表S的元素重新排列为与S本身一一对应的关系。长度为n的字符串为n!排列。
资料来源:Mathword

以下是字符串ABC的排列。

我们在这里讨论了使用回溯打印给定字符串的所有排列的C实现。在本文中,将讨论使用STL的C++实现。

方法1(使用rotate())
std :: rotate函数旋转向量/字符串的元素,以使传递的中间元素成为第一个。例如,如果我们将“ ABCD”作为中间元素作为第二个元素调用rotate,则字符串变为“ BCDA”,如果我们再次将“中间”作为第二元素调用“ rotate”,则字符串变为“ CDAB”。请参考此示例程序。

图片(8)

下面是C++的实现。

C++
// C++ program to print all permutations with
// duplicates allowed using rotate() in STL
#include 
using namespace std;
 
// Function to print permutations of string str,
// out is used to store permutations one by one
void permute(string str, string out)
{
    // When size of str becomes 0, out has a
    // permutation (length of out is n)
    if (str.size() == 0)
    {
        cout << out << endl;
        return;
    }
 
    // One be one move all characters at
    // the beginning of out (or result)
    for (int i = 0; i < str.size(); i++)
    {
        // Remove first character from str and
        // add it to out
        permute(str.substr(1), out + str[0]);
 
        // Rotate string in a way second character
        // moves to the beginning.
        rotate(str.begin(), str.begin() + 1, str.end());
    }
}
 
// Driver code
int main()
{
    string str = "ABC";
    permute(str, "");
    return 0;
}


C++
// C++ program to print all permutations with
// duplicates allowed using next_permutation
#include 
using namespace std;
 
// Function to print permutations of string str
// using next_permutation
void permute(string str)
{
    // Sort the string in lexicographically
    // ascending order
    sort(str.begin(), str.end());
 
    // Keep printing next permutation while there
    // is next permutation
    do {
       cout << str << endl;
    } while (next_permutation(str.begin(), str.end()));
}
 
// Driver code
int main()
{
    string str = "CBA";
    permute(str);
    return 0;
}


输出
ABC
ACB
BCA
BAC
CAB
CBA

方法2(使用next_permutation)
我们可以使用next_permutation修改字符串,以便按字典顺序存储下一个排列。如果当前字符串在词典上是最大的,即“ CBA”,则next_permutation返回false。

我们首先对字符串排序,以便将其转换为按字典顺序排列的最小排列。然后,我们一个接一个地调用next_permutation,直到返回false为止。

C++

// C++ program to print all permutations with
// duplicates allowed using next_permutation
#include 
using namespace std;
 
// Function to print permutations of string str
// using next_permutation
void permute(string str)
{
    // Sort the string in lexicographically
    // ascending order
    sort(str.begin(), str.end());
 
    // Keep printing next permutation while there
    // is next permutation
    do {
       cout << str << endl;
    } while (next_permutation(str.begin(), str.end()));
}
 
// Driver code
int main()
{
    string str = "CBA";
    permute(str);
    return 0;
}
输出
ABC
ACB
BAC
BCA
CAB
CBA