按詞典順序在 C++ 中列印字串的所有組合


在此問題中,給了我們一個字串 str,我們需要按詞典順序列印字元的所有組合。

我們舉個例子,以便更好地理解這個問題 −

Input: str = ‘XYZ’
Output :
X
XY
XYZ
XZ
XZY
Y
YX
YXZ
YZ
YZX
Z
ZX
ZXY
ZY
ZYX

為了解決這個問題,我們將列印字串中所有字元的組合。為此,我們需要一個 map 資料結構來儲存字串的字元。對於實現,我們需要使用回溯法來跟蹤所有組合。

例項

 實際示例

#include <bits/stdc++.h>
using namespace std;
void printResult(char* result, int len);
void findstringCombination(char result[], char str[], int count[],int level, int
size, int length) ;
void printCharCombination(string str);
int main(){
   string str = "ABC";
   cout<<"The combination of characters of the string :\n";
   printCharCombination(str);
   return 0;
}
void findstringCombination(char result[], char str[], int count[],int level, int size, int length){
   if (level == size)
      return;
   for (int i = 0; i < length; i++) {
      if (count[i] == 0)
         continue;
      count[i]--;
      result[level] = str[i];
      printResult(result, level);
      findstringCombination(result, str, count, level + 1, size, length);
      count[i]++;
   }
}
void printCharCombination(string str){
   map<char, int> mp;
   for (int i = 0; i < str.size(); i++) {
      if (mp.find(str[i]) != mp.end())
         mp[str[i]] = mp[str[i]] + 1;
      else
         mp[str[i]] = 1;
   }
   char* input = new char[mp.size()];
   int* count = new int[mp.size()];
   char* result = new char[str.size()];
   map<char, int>::iterator it = mp.begin();
   int i = 0;
   for (it; it != mp.end(); it++) {
      input[i] = it->first;
      count[i] = it->second;
      i++;
   }
   int length = mp.size();
   int size = str.size();
   findstringCombination(result, input, count, 0, size, length);
}
void printResult(char* result, int len){
   for (int i = 0; i <= len; i++)
      cout<<result[i];
   cout<<endl;
}

輸出

字串字元的組合 −

A
AB
ABC
AC
ACB
B
BA
BAC
BC
BCA
C
CA
CAB
CB
CBA

更新於: 17-Jan-2020

392 檢視

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告