I'm having difficulty understanding the recursion workflow of the following function and how it traverses through the array sorting the permutations.
One particular thing that's getting me stumped is how the 'return [nums[:]]' call behaves when it's in a recursive function. Since line 9 calls itself again until 'start == 2', when does it continue executing the lines past line 9 and for which of the recursive functions does it execute those proceeding lines?
Sorry if my question is a little confusing, I just started learning Python recently and would like to get a better understanding of how 'return' calls work in recursive functions. Any advice is appreciated!
class Solution(object):
def _permuteHelper(self, nums, start=0):
if start == len(nums) - 1:
return [nums[:]]
result = []
for i in range(start, len(nums)):
nums[start], nums[i] = nums[i], nums[start]
result += self._permuteHelper(nums, start + 1)
nums[start], nums[i] = nums[i], nums[start]
return result
def permute(self, nums):
return self._permuteHelper(nums)
print(Solution().permute([1, 2, 3]))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]