使用迭代法獲取字串的所有排列?


在本節中,我們將瞭解如何獲得字串的所有排列。遞迴方法非常簡單。它使用回溯過程。但在這裡,我們將使用迭代法。

字串 ABC 的所有排列就像 {ABC, ACB, BAC, BCA, CAB, CBA}。我們來看一下演算法來更好地理解。

演算法

getAllPerm(str)

begin
   sort the characters of the string
   while true, do
      print the string str
      i := length of str – 1
      while str[i - 1] >= str[i], do
         i := i – 1
         if i is 0, then
            return
         end if
      done
      j := length of str – 1
      while j > i AND str[j] <= str[i – 1], do
         j := j – 1
      done
      exchange the characters from position str[i - 1], str[j]
      reverse the string.
   done
end

示例

 線上示例

#include <iostream>
#include <algorithm>
using namespace std;
void getAllPerm(string str){
   sort(str.begin(), str.end());
   while (true){
      cout << str << endl;
      int i = str.length() - 1;
      while (str[i-1] >= str[i]){
         if (--i == 0)
         return;
      }
      int j = str.length() - 1;
      while (j > i && str[j] <= str[i - 1])
      j--;
      swap(str[i - 1], str[j]);
      reverse (str.begin() + i, str.end());
   }
}
int main(){
   string str = "WXYZ";
   getAllPerm(str);
}

輸出

WXYZ
WXZY
WYXZ
WYZX
WZXY
WZYX
XWYZ
XWZY
XYWZ
XYZW
XZWY
XZYW
YWXZ
YWZX
YXWZ
YXZW
YZWX
YZXW
ZWXY
ZWYX
ZXWY
ZXYW
ZYWX
ZYXW

更新時間: 30-07-2019

659 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.