如何透過使用 C# 語言進行回溯法,找出字串的所有排列?


找到第一個位置的字元並用第一個字元交換其餘字元。比如在 ABC 中,在第一次迭代中,透過用 A 分別與 A、B 和 C 交換,形成了三個字串:ABC、BAC 和 CBA。對其餘字元重複步驟,例如固定第二個字元 B,依此類推。現在再次進行交換以返回到前一個位置。在 ABC 中,我們透過再次固定 B 形成 ABC,並且我們回溯到前一個位置並將 B 與 C 交換。因此,現在我們得到 ABC 和 ACB。

示例

 即時演示

using System;
namespace ConsoleApplication{
   public class BackTracking{
      public void StringPermutation(string word, int start, int end){
         if (start == end){
            Console.WriteLine(word);
         }
         else{
            for (int i = start; i <= end; i++){
               Swap(ref word, start, i);
               StringPermutation(word, start + 1, end);
               Swap(ref word, start, i);
            }
         }
      }
      private void Swap(ref string word, int start, int end){
         char[] arr = word.ToCharArray();
         char temp = arr[start];
         arr[start] = arr[end];
         arr[end] = temp;
         word = new string(arr);
      }
   }
   class Program{
      static void Main(string[] args){
         BackTracking b = new BackTracking();
         b.StringPermutation("ABC", 0, 2);
      }
   }
}

輸出

ABC
ACB
BAC
BCA
CBA
CAB

更新於: 2021 年 8 月 27 日

719 次瀏覽

開啟你的 職業

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.