[英]Algorithm to print all combination of letters of the given string in lexicographical order
I tried to create the code to generate all possible combination of the given string in the lexicographical order: 我试图创建代码以按字典顺序生成给定字符串的所有可能组合:
The code that I wrote is: 我写的代码是:
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;
}
Suppose the string is : abcde 假设字符串是:abcde
My code is not generating combinations like: 我的代码未生成如下组合:
abd
abe
The output I am getting for the string abcde are: 我得到的字符串abcde的输出是:
a
ab
abc
abcd
abcde
ac
ad
ae
b
bc
bcd
bcde
bd
be
c
cd
cde
ce
d
de
e
My output does not contains strings like : abd abe
我的输出不包含以下字符串: abd abe
Hope this makes the question clear 希望这可以使问题清楚
How to generate all these combinations using an efficient algorithm 如何使用高效算法生成所有这些组合
This is a simple recursive approach: 这是一种简单的递归方法:
#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;
}
Maybe not the most efficient way of doing it, but a short and simple one. 可能不是最有效的方法,而是一种简短的方法。 Keep in mind, that enumerating all combinations has a complexity of O(2 n ) anyway. 请记住,枚举所有组合的复杂度始终为O(2 n ) 。 So there exists no efficient algorithm at all. 因此根本不存在有效的算法。
Following may help: 以下内容可能会有所帮助:
bool increase(std::vector<bool>& bs)
{
for (std::size_t i = 0; i != bs.size(); ++i) {
bs[i] = !bs[i];
if (bs[i] == true) {
return true;
}
}
return false; // overflow
}
template <typename T>
void PowerSet(const std::vector<T>& v)
{
std::vector<bool> bitset(v.size());
do {
for (std::size_t i = 0; i != v.size(); ++i) {
if (bitset[i]) {
std::cout << v[i] << " ";
}
}
std::cout << std::endl;
} while (increase(bitset));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.