Problem Description
1 | Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. |
Solution
Base case
To begin with, let’s consider the case that the size of the array is fixed. If the array size is 3, for instance: arr = [1,2,3]
The permutations of the array are:
1 | [[1,2,3], |
If the size of the array is fixed, we can use nested for loops to generate the output. How many for
loops are required? It’s easy to see, the answer equals the array size. The code is as follows:
1 | class Solution { |
However, if the array size is variable, how to generalize to all possible results? A recursive algorithm is needed.
Generalization
We still take the previous example. The problem is, how to generate the help arrays recursively?
The first help array, obviously, is [1,2,3]
. And the second is [1,3,2]
. How to get [1,3,2]
from [1,2,3]
? It looks pretty tricky at first glance, but by using recursion, everything gets clearer! The subarrays [2,3]
and [3,2]
, are actually permutations of the array [2,3]
, which is the help array discarding the first element 1! So to generate the output we just need to concatenate two arrays, by pseudo-code:
1 | (elements already permuted) |
The pseudo-code has already shown us that we need to know if the currently visited element in nums is visited or not. If it is visited, it should be put into elements already permuted array, otherwise, it should be put into the rest elements array and wait for permuting. How to do this?
First, we need a bucket that stores an array of bool type to mark if each element in the array is visited.
And try to visit every element in the nums. This is simple, so we’ll jump to the next step. If the current element has not visited yet, mark the Bucket[i] = true
, add it to the array already permuted, and permute the rest elements. After permuting the rest elements, and reset Bucket[i]
to false.
1 | if(Bucket[i] == false) |
If the current element is visited, then is nothing worthy to be mentioned, just continue.
Lastly, every recursion has a return condition. When do we return? Obviously, when the size of the array that stores the result equals to nums!
1 | // the help_arr has already reaches to the end |
Now the whole algorithm completes. The full code is as follows:
1 | class Solution{ |