This is my solution to the "Permutations" problem from Leetcode:
Given a collection of distinct numbers, return all possible permutations.
I know this is a common routine that can be done much faster using itertools.permutations but I want to write it to learn the algorithm itself.
I would like any general feedback on the implementation of the recursive algorithm. But I am also curious whether I should use an instance helper method as it is now, or make the helper method a class or static method. If someone can show me how to re-write the helper method as a class or static method that would be appreciated.
class Solution(object):
def permute(self, nums):
res = []
self._permuteHelper( nums, 0, res)
return res
def _permuteHelper(self, nums, start, results): #helper method
if start >= len(nums):
results.append(nums[:])
else:
for i in range(start, len(nums)):
nums[i], nums[start] = nums[start], nums[i]
self._permuteHelper(nums, start +1, results)
nums[start], nums[i] = nums[i], nums[start]
s = Solution()
nums = [1, 2, 3]
print s.permute(nums)
There are a lot of suggestions in the comments and answers about using library functions. For programming challenge, I am not interested in copying and pasting library functions. Yes, this is re-inventing the wheel if you want to call it that!