Skip to content

47. Permutations II

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

js
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permuteUnique = function(nums) {
  if (nums.length === 1) {
    return [nums]
  }

  var set = new Set()
  var result = []

  for (let i = 0; i < nums.length; i++) {
    if (set.has(nums[i])) {
      continue
    }
    set.add(nums[i])

    var copy = nums.slice()
    var n = copy.splice(i, 1)[0]

    permuteUnique(copy).forEach(arr => {
      arr.unshift(n)
      result.push(arr)
    })
  }

  return result
}
py
class Solution(object):

    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) == 1:
            return [nums]
        lookup = set()
        result = []
        for i in range(len(nums)):
            if nums[i] in lookup:
                continue
            lookup.add(nums[i])
            for j in self.permuteUnique(nums[:i] + nums[i + 1:]):
                result.append([nums[i]] + j)
        return result