
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements