This will lead to the creation of the set you need, but in a different order (I sort alphabetically at the end, you also want to sort by length).
As a result, you will receive:
a ab alphabet ABCD ABCDE ABCE ... d de e
So, all possible subsets (except the empty string), while maintaining the order of the original list.
The idea is to add each item to the growing list. With each new element, first add it and then add it to all existing elements.
So start with 'a'.
Go to 'b'. Add it to the list. Now we have {'a', 'b'}.
Add it to existing elements so that we have "ab". Now we have {'a', 'b', 'ab'}.
Then "c" and add it to existing elements to get "ac", "bc", "abc": {'a', 'b', 'ab', 'c', 'ac', 'bc', abc '}. So, until we finish.
string set = "abcde"; // Init list List<string> subsets = new List<string>(); // Loop over individual elements for (int i = 1; i < set.Length; i++) { subsets.Add(set[i - 1].ToString()); List<string> newSubsets = new List<string>(); // Loop over existing subsets for (int j = 0; j < subsets.Count; j++) { string newSubset = subsets[j] + set[i]; newSubsets.Add(newSubset); } subsets.AddRange(newSubsets); } // Add in the last element subsets.Add(set[set.Length - 1].ToString()); subsets.Sort(); Console.WriteLine(string.Join(Environment.NewLine, subsets));
Sapph source share