Advanced Recursion Techniques
Lesson Overview
Quick Example
To give you a small taste of what is in store, let's take a look at a recursive function that generates all permutations of a list of numbers. The strategy here is to use a method known as backtracking.
Backtracking is a general algorithm for finding all (or some) solutions to computational problems by incrementally building candidates and abandoning a candidate as soon as it determines that the candidate cannot possibly be completed as a valid solution.
In our example, we use a MutableList to store the numbers so that we can modify them in place. At each recursion level, we choose which number should go at position first by swapping nums[first] with each element from first to the end. We then move one level deeper into the recursion to fix the next position and finally swap the elements back to reset the state for the next iteration. Once we reach the end of the list, we create a copy of the current state of the list and add it to our results.
