📌  相关文章
📜  任何长度的所有可能的字符串,可以从一个给定的字符串来形成

📅  最后修改于: 2021-04-23 07:21:54             🧑  作者: Mango

给定的不同的字符的字符串,打印任何长度的所有可能的字符串,可以从给定的字符串的字符来形成。

例子:

Input: abc
Output: a b c abc ab ac bc bac bca 
         cb ca ba cab cba acb

Input: abcd
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 

所有字符串的生成包括以下步骤。
1)生成给定字符串的所有子序列。
2)对于每个子序列“ subs”,打印“ subs”的所有排列

下面是C++的实现。它使用C++中的next_permutation函数。

C/C++
/*  C++ code to generate all possible strings
    that can be formed from given string */
#include
using namespace std;
  
void printAll(string str)
{
    /* Number of subsequences is (2**n -1)*/
    int n = str.length();
    unsigned int opsize = pow(2, n);
  
    /* Generate all subsequences of a given string.
       using counter 000..1 to 111..1*/
    for (int counter = 1; counter < opsize; counter++)
    {
        string subs = "";
        for (int j = 0; j < n; j++)
        {
            /* Check if jth bit in the counter is set
                If set then print jth element from arr[] */
            if (counter & (1<


Python3
# Python3 code to generate all possible strings
# that can be formed from given string 
from itertools import permutations 
    
def printAll( st):
      
    # Number of subsequences is (2**n -1)
    n = len(st)
    opsize = pow(2, n)
   
    # Generate all subsequences of a given string.
    #  using counter 000..1 to 111..1
    for counter in range(1, opsize):
      
        subs = ""
        for j in range(n):
          
            # Check if jth bit in the counter is set
            #   If set then print jth element from arr[] 
            if (counter & (1<


输出:

a b ab ba c ac ca bc cb abc acb bac bca cab cba