Actually you have here 3 phases:
- Select the letters from the input word. I do that by using counter which is promoted, then looking at it as bits representation, if bit i is '1', then I choose character i. If '0' then don't.
- Generate permutations based on selected letters. Here I use recursive helper function
Permutations - Remove duplicates from the final result. Duplicates can occure in case your original word duplicate characters. for example: "catt"
Solution:
static void Main(string[] args) { string word = "catt"; List<string> result = new List<string>(); int total = (int)Math.Pow(2, word.Length); for (int i = 0; i < total; i++) { string tempWord = string.Empty; // pick the letters from the word for (int temp = i, j = 0; temp > 0; temp = temp >> 1, j++) { if ((temp & 1) == 1) { tempWord += word[j]; } } // generate permutations from the letters List<string> permutations; Permutations(tempWord, out permutations); foreach (var prm in permutations) result.Add(prm); } // remove duplicates var resultWithoutDuplicates = result.Distinct(); foreach (var w in resultWithoutDuplicates) Console.WriteLine(w); Console.ReadLine(); } static void Permutations(string str, out List<string> result) { result = new List<string>(); if (str.Length == 1) { result.Add(str); return; } for (int i = 0; i < str.Length; i++) { char c = str[i]; string temp = str.Remove(i, 1); List<string> tempResult; Permutations(temp, out tempResult); foreach (var tempRes in tempResult) result.Add(c + tempRes); } }
Instead of doing the final step (remove duplication) we can use hashset instead of list, to ensure no duplication during results adding to final data structure.
Hope it helps.