卖萌的弱渣

I am stupid, I am hungry.

Permutations II

Given a list of numbers with duplicate number in it. Find all unique permutations.

Example

For numbers [1,2,2] the unique permutations are:

1
2
3
4
5
[
  [1,2,2],
  [2,1,2],
  [2,2,1]
]

Solution

  • DFS
(Permutations2.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
    """
    @param nums: A list of integers.
    @return: A list of unique permutations.
    """
    def permutation(self,entry,result,solution):
        if len(entry) == 0:
            if solution not in result:
                result.append(solution[:])
            return
        for i in range(len(entry)):
            element = entry[i]
            solution.append(element)
            entry.pop(i)
            self.permutation(entry,result,solution)
            solution.pop()
            entry.insert(i,element)
        return

    def permuteUnique(self, nums):
        # write your code here
        result = []
        if nums == None or len(nums) == 0:
            return result
        self.permutation(nums,result,[])
        return result