Python beat 100%! 10+ lines. Recursion is always elegant

  • 0

    Nothing much to talk about, just look at the code.

    class Solution(object):
        def permute(self, nums):
            :type nums: List[int]
            :rtype: List[List[int]]
            res = []
            # base cases
            if len(nums) == 2:
                return [[nums[0], nums[1]], [nums[1], nums[0]]]
            if len(nums) == 1:
                return [[nums[0]]]
            # recursion begins
            for i in range(len(nums)):
                left = nums[0:i] + nums[i + 1:]
                num = nums[i]
                for subRes in self.permute(left):
                    res.append([num] + subRes)
            return res

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.