I have the following code which uses recursion to create a list of all permutations of an input string. I'm struggling to understand how it works. The idea of the algorithm is that the first char is taken, then it is added to each place of all permutations of the remaining characters. I don't understand how the recursion is working. If you can explain this succinctly I'd be very appreciative. This is not a duplicate question as I am looking for how this algorithm is working *not * how to get permutations of a string. I've tried stepping through and if you F11 this and follow the local variable changes, it is most confusing.
public static List<string> GetPermutations(string s)
{
var permutations = new List<string>();
if (s == null)
{
// error case
return null;
}
if (s.Length == 0)
{
// base case
permutations.Add("");
return permutations;
}
char first = s[0]; // get the first character
string remainder = s.Substring(1); // remove the first character
List<string> words = GetPermutations(remainder);
foreach (string word in words)
{
for (int j = 0; j <= word.Length; j++)
{
permutations.Add(insertCharAt(word, first, j));
}
}
return permutations;
}
public static string insertCharAt(string word, char c, int i)
{
string start = word.Substring(0, i);
string end = word.Substring(i);
return start + c + end;
}
}