Using Recursion on a Medium Level LeetCode: Permutations
In this series, I will explain my thought process of figuring out one way to solve a particular LeetCode problem and then provide the JavaScript code.
The objective is to find out all combinations of a certain array of numbers.
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
I’m writing this article for those who are already familiar with recursion, but want to become better at implementing it on their own.
First, let’s just take care of the small stuff. We’ll need a variable to hold our result. Then, we’ll return it at the very end of the function. You can name your inner function whatever you want, but I like to use “traverse.”
Before jumping into the code, let’s do a quick review of slice vs splice.
Slice creates and returns a new array with a given subset.
Splice changes the original array with a given subset.
Each time we call the traverse function, we’re specifying what we have in progress as the first parameter. It’s pretty common to see this referred to as “temp.” Then, we have the second parameter, which I like to think of as everything else (theRest) or the next possible remaining values to pick from.
Visualizing Recursion
If it’s difficult to envision, I’ve included the full code here with printed statements to show exactly what is going on in each step. However, I would highly recommend running the code in your IDE and putting breakpoints on lines 4, 6, and 12. Then, run your debugger to see each step take place.
Sometimes it helps to actually draw out what you’re doing on paper. This is an example of how I brainstormed a different recursion problem (how many ways can you add up to 4).
If you’re interested in going on a deep dive into this problem and backtracking, I recommend reading this article by Li Yin.
Anyway, there are many ways to solve a problem, so feel free to share your thoughts in the comments below!
☕️If you enjoyed this article, please consider tipping here: