LeetCode 46. Permutations

Description

https://leetcode.com/problems/permutations/

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Explanation

use hashmap track visited

Python Solution

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        result = []
        
        nums = list(sorted(nums))
        visited = set()
        self.helper(nums, visited, [], result)
        
        return result
    
    def helper(self, nums, visited, subset, result):

        if len(subset) == len(nums):
            result.append(list(subset))        
        
        for i in range(0, len(nums)):
            if (nums[i] in visited):
                continue
                
            subset.append(nums[i])
            visited.add(nums[i])
            
            self.helper(nums, visited, subset, result)
            
            visited.remove(nums[i])
            subset.pop()
  • Time complexity: O(2^N).
  • Space complexity: O(N).

One Thought to “LeetCode 46. Permutations”

Leave a Reply

Your email address will not be published. Required fields are marked *