Simple DFS python, easier than the solutions with high votes. 91%


  • 0
    L
    class Solution:
        """
        @param nums: A list of integers.
        @return: A list of unique permutations.
        """
        def permuteUnique(self, nums):
            # write your code here
            res = []
            self.dfs(res, [], sorted(nums))
            return res
        def dfs(self,res, path, nums):
            if not nums:
                res.append(path)
            for i in range(len(nums)):
                if i > 0 and nums[i] == nums[i-1]:
                    continue
                self.dfs(res, path + [nums[i]], nums[:i] + nums[i+1:])
    
    

    Permutations I is just as similar:

    class Solution:
        """
        @param nums: A list of integers.
        @return: A list of unique permutations.
        """
        def permuteUnique(self, nums):
            # write your code here
            res = []
            self.dfs(res, [], nums)
            return res
        def dfs(self,res, path, nums):
            if not nums:
                res.append(path)
            for i in range(len(nums)):
                self.dfs(res, path + [nums[i]], nums[:i] + nums[i+1:])

Log in to reply
 

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