c++ - 按字典顺序打印给定字符串的所有字母组合的算法

标签 c++ string combinations powerset lexicographic

我尝试创建代码以按字典顺序生成给定字符串的所有可能组合:

我写的代码是:

void get(char *n)
 {
    int l=strlen(n); 
    sort(n,n+l);
    int k=0,m,i,j,z;

    while(k<l)
    {
        m=k;

        for(i=k;i<l;i++)
        {
            for(j=k;j<=i;j++)
                cout<<n[j];

            cout<<"\n";
        }

        for(z=m+2;z<l;z++)
            cout<<n[m]<<n[z]<<"\n";  

        k++;
    }
 }


int main() 
 {
    char n[100];
    cin>>n;
    get(n);
    return 0;
 }

假设字符串是:abcde

我的代码没有生成如下组合:

abd
abe

我得到的字符串 abcde 的输出是:

a 
ab
abc 
abcd 
abcde 
ac 
ad
ae 
b 
bc 
bcd 
bcde 
bd 
be 
c 
cd 
cde 
ce 
d 
de 
e

我的输出不包含像这样的字符串:abd abe

希望这能把问题弄清楚

如何使用高效算法生成所有这些组合

最佳答案

这是一个简单的递归方法:

#include <string>
#include <iostream>
using namespace std;

void get( string str, string res ) {

   cout << res << endl;

   for( int i = 0; i < str.length(); i++ )
      get( string(str).erase(i,1), res + str[i] );
}

int main( int argc, char **argv) {

   string str = "abcde";
   get( str, "" );  
   return 0;
}

也许这不是最有效的方法,但却是一种简短的方法。请记住,无论如何,枚举所有组合的复杂度为 O(2n)。所以根本不存在高效的算法。

关于c++ - 按字典顺序打印给定字符串的所有字母组合的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29059461/

相关文章:

ruby - 在 Ruby 中将数组的数组组合成所有可能的组合,仅向前

algorithm - 所有组合按列顺序

c++ - static_cast<unsigned>(signed) 与 std::bit_cast<unsigned>(signed) 之间有区别吗?

javascript - 仅使用 Y 数小于 X 的所有可能性?

c# - 在 C# 程序中使用 C++11

c++ - 计算字符串中子字符串的出现次数

r - 从不规则间隔的 pdf 中提取字符串到整洁的 R 数据帧中

c++ 在不使用 char 数组的情况下将 std::string 转换为 int、double 等

c++ - 是 int a[10]={0,1,2,3,4,5,6,7,8,9};与 C++ 中的 int *a={0,1,2,3,4,5,6,7,8,9} 相同吗?

c++ - 验证并验证 NoMoreInteractions 到 gtest