forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutations-ii.py
46 lines (39 loc) · 1.28 KB
/
permutations-ii.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Time: O(n * n!)
# Space: O(n)
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
result = []
used = [False] * len(nums)
self.permuteUniqueRecu(result, used, [], nums)
return result
def permuteUniqueRecu(self, result, used, cur, nums):
if len(cur) == len(nums):
result.append(cur + [])
return
for i in xrange(len(nums)):
if used[i] or (i > 0 and nums[i-1] == nums[i] and not used[i-1]):
continue
used[i] = True
cur.append(nums[i])
self.permuteUniqueRecu(result, used, cur, nums)
cur.pop()
used[i] = False
class Solution2(object):
# @param num, a list of integer
# @return a list of lists of integers
def permuteUnique(self, nums):
solutions = [[]]
for num in nums:
next = []
for solution in solutions:
for i in xrange(len(solution) + 1):
candidate = solution[:i] + [num] + solution[i:]
if candidate not in next:
next.append(candidate)
solutions = next
return solutions