Find All Permutations of a String Using Backtracking



Find the character in the first position and swap the rest of the character with the first character. Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A with A, B and C respectively. Repeat step for the rest of the characters like fixing second character B and so on. Now swap again to go back to the previous position. from ABC, we formed ABC by fixing B again, and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB.

Example

 Live Demo

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);
      }
   }
}

Output

ABC
ACB
BAC
BCA
CBA
CAB
Updated on: 2021-08-27T13:15:22+05:30

826 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements