从给定的字符串可以构成任何长度的所有可能的字符串?
在本节中,我们将看到如何生成所有可能的任何长度的字符串,这将使用每种字符组合来构成字符串。例如,如果字符串是ABC,则它将生成-{A,B,C,AB,BA,BC,CB,CA,AC,ABC,ACB,BAC,BCA,CAB,CBA}
让我们看一个例子来了解这个想法。
算法
printAllString(str)
Begin
n := length of the string str
count is 2^n – 1
for each number 0 to count, do
sub_str := empty string
for j in range 0 to n, do
if jth bit of the counter is set, then
concatenate jth character of str with sub_str
end if
done
repeat:
print sub_string
until next permutation of sub_string is not completed
done
End示例
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
void printAllString(string str) {
int n = str.size();
unsigned int count = pow(2, n);
for (int counter = 1; counter <count; counter++) { //generate 2^n - 1 strings
string subs = "";
for (int j = 0; j < n; j++) {
if (counter & (1<<j)) //when the jth bit is set, then add jth character
subs.push_back(str[j]);
}
do{
cout << subs << endl;
}
while (next_permutation(subs.begin(), subs.end()));
}
}输出结果
A B AB BA C AC CA BC CB ABC ACB BAC BCA CAB CBA D AD DA BD DB ABD ADB BAD BDA DAB DBA CD DC ACD ADC CAD CDA DAC DCA BCD BDC CBD CDB DBC DCB ABCD ABDC ACBD ACDB ADBC ADCB BACD BADC BCAD BCDA BDAC BDCA CABD CADB CBAD CBDA CDAB CDBA DABC DACB DBAC DBCA DCAB DCBA
热门推荐
10 日语送考祝福语简短
11 虎年台词祝福语大全简短
12 生女儿的祝福语简短
13 亲姐姐祝福语简短英文
14 新年祝福语长篇文案简短
15 美女蛋糕祝福语简短英文
16 同事辞职正常祝福语简短
17 男士送花祝福语大全简短
18 送女士祝福语长辈简短