Home > Backend Development > C++ > Given a string, list all possible length strings it consists of

Given a string, list all possible length strings it consists of

WBOY
Release: 2023-08-27 20:05:06
forward
883 people have browsed it

Given a string, list all possible length strings it consists of

In this section we will see how to generate all possible strings of any length, which will take every combination of characters to generate the string. For example, if the string is ABC, then it will generate - {A,B,C,AB,BA,BC,CB,CA,AC,ABC,ACB,BAC,BCA,CAB,CBA}

Let's see an example to understand.

Algorithm

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
Copy after login

Example

#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()));
   }
}
Copy after login

Output

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
Copy after login

The above is the detailed content of Given a string, list all possible length strings it consists of. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template