用 C++ 列印給定字串的所有不同排列,其中包含重複項


在此問題中,我們給定了一個可能包含重複字元的字串。我們的任務是列印字串的所有不同排列。

讓我們舉個例子來理解問題 −

Input: string = “XYZ”
Output: XYZ XZY YXZ YZX ZYX ZXY

為了解決這個問題,我們必須固定字串的一個元素。然後迭代字串的所有元素。

示例

實現我們解決方案的程式,

 即時演示

#include <string.h>
#include <iostream>
using namespace std;
int compare(const void* a, const void* b) {
   return (*(char*)a - *(char*)b);
}
void swapChar(char* a, char* b) {
   char t = *a;
   *a = *b;
   *b = t;
}
int findCeil(char str[], char first, int l, int h) {
   int ceilIndex = l;
   for (int i = l + 1; i <= h; i++)
      if (str[i] > first && str[i] < str[ceilIndex])
         ceilIndex = i;
   return ceilIndex;
}
void printPermutations(char str[]) {
   int size = strlen(str);
   qsort(str, size, sizeof(str[0]), compare);
   bool isFinished = false;
   while (!isFinished) {
      static int x = 1;
      cout<<str<<"\t";
      int i;
      for (i = size - 2; i >= 0; --i)
         if (str[i] < str[i + 1])
      break;
      if (i == -1)
         isFinished = true;
      else {
         int ceilIndex = findCeil(str,
         str[i], i + 1, size - 1);
         swapChar(&str[i], &str[ceilIndex]);
         qsort(str + i + 1, size - i - 1,
         sizeof(str[0]), compare);
      }
   }
}
int main() {
   char str[] = "SNGY";
   cout<<"All permutations of the string"<<str<<" are :\n";
   printPermutations(str);
   return 0;
}

輸出

All permutations of the stringSNGY are −
GNSY GNYS GSNY GSYN GYNS GYSN NGSY NGYS NSGY NSYG NYGS NYSG SGNY SGYN SNGY SNYG SYGN SYNG YGNS YGSN YNGS YNSG YSGN YSNG

更新於: 22-1 月 -2020

236 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.