首頁  >  文章  >  後端開發  >  給定一個字串,將其組成的所有可能長度的字串都列出來

給定一個字串,將其組成的所有可能長度的字串都列出來

WBOY
WBOY轉載
2023-08-27 20:05:06822瀏覽

給定一個字串,將其組成的所有可能長度的字串都列出來

在本節中,我們將看到如何產生任意長度的所有可能字串,這將採用每個字元的組合來產生字串。例如,如果字串是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
#

以上是給定一個字串,將其組成的所有可能長度的字串都列出來的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除