I just can't wrap my head around recursion. I understand all of the concepts (breaking solution into smaller cases) and I can understand solutions after I read them over and over again. But I can never figure out how to use recursion to solve a problem. Is there any systematic way to come up with a recursive solution?
Can someone please explain to me their thought process when they try to solve the following recursive problem: "Return all permutations of a string using recursion".
Here is an example of my thought process to solve this problem.
- Check if the Strings length is equal to 2. If it is, swap the values (base case)
- Else: for each first value return the first value + recursive(string without first value)
Can somebody please give me some tips to change my thought process or to think of recursion in a better way so I can solve recursive problems without just looking up the answers.
EDIT: Here is my thought process in coding another solution to this problem.
- Base case is when the strings length = 0
- If its not the base case, then for each first letter of the string, insert the first letter into every position of every permutation of the string without the first letter
- Ex: string is "abc", first letter is a, so insert a in every position of the permutations of "bc". [bc, cb] => [abc, bac, bca, acb, cab, cba]
Pseudocode
permutation(String s, List l) {
if(s.length() == 0) {
return list;
}
else {
String a = s.firstLetter();
l = permutation(s.substring(1, s.length) , l)
for(int i = 0; i < s.length(); i++) {
// loop that iterates through list of permutations
// that have been "solved"
for(int j=0; j < l.size(); j++) {
// loop that iterates through all positions of every
// permutation and inserts the first letter
String permutation Stringbuilder(l[i]).insert(a, j);
// insert the first letter at every position in the
// single permutation l[i]
l.add(permutation);
}
}
}
}