Permutations 2 LeetCode – Python Solution

LeetCode has a Medium coding Problem in Its’ Algorithm Section “Permutations 2 LeetCode”. Today We are going to solve this problem in Python. LeetCode Link of the Problem is HERE

Questions

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Examples

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

Constraints:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

A solution to Permutations 2 leetcode

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        result = []
        self.permutation(nums, [],result)
        return result

    def permutation(self, numbers, curr, result):
        if len(numbers) == 0:
            result.append(curr)

        for i in range(len(numbers)):
            if i > 0 and numbers[i] == numbers[i-1]:
                continue
            self.permutation(numbers[0:i]+numbers[i+1:], curr + [numbers[i]], result)
        

Success:

Runtime: 65 ms, faster than 56.15% of Python online submissions for Permutations II

Memory Usage: 13.6 MB, less than 86.58% of Python online submissions for Permutations II.

READ MORE

Python-related posts Visit HERE

C++ related posts Visit HERE

Databases related posts Visit HERE

Data Structures related posts visit HERE

Algorithms related posts visit HERE

Data Science related posts visit HERE