Skip to content

Latest commit

 

History

History
41 lines (32 loc) · 1.18 KB

47.-permutations-ii.md

File metadata and controls

41 lines (32 loc) · 1.18 KB
description
Back-tracking

47. Permutations II

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

Analysis

This is very much similar to the previous one. The only difference is that we need to keep in mind there might be duplicates in this list. But all we have to do is to take care of them using the same code we have been using for long.

            if i>0 and candidates[i-1]==candidates[i]:
                continue

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        ans=[]
        answer=[]
        nums.sort()
        self.helper(nums,ans,answer)
        return answer
        
    def helper(self,candidates, ans,answer):
        if not candidates:
            answer.append(ans)
            return
        for i in range(len(candidates)):
            if i>0 and candidates[i-1]==candidates[i]:
                continue
                
            temp=candidates.copy()
            temp.remove(candidates[i])
            self.helper(temp,ans+[candidates[i]],answer)