-
Notifications
You must be signed in to change notification settings - Fork 0
/
47. Permutations II
47 lines (47 loc) · 1.63 KB
/
47. Permutations II
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
46
47
# 09:19 -- 09:51
# run time: 129ms, 28%; 109ms, 59%; 138ms, 22%
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort ()
lens = len(nums)
if lens == 1:
return [nums]
if lens == 0:
return nums
if lens == 2:
if nums[0] == nums[1]:
#print nums, nums
return [nums]
else:
#print [[nums[0], nums[1]], [nums[1], nums[0]]], nums
return [[nums[0], nums[1]], [nums[1], nums[0]]]
else:
output = []
for i in xrange(lens):
if i == 0:
temp_nums = nums[1:]
result = self.permuteUnique (temp_nums)
if type(result[0]) != type(1):
for x in result:
output.append( [nums[i]] + x)
else:
output.append ([nums[i]] + result)
elif nums[i] == nums[i - 1]:
continue
else:
if i == lens:
temp_nums = nums[:-1]
else:
temp_nums = nums[:i] + nums[i+1 :]
result = self.permuteUnique (temp_nums)
if type(result[0]) != type(1):
for x in result:
output.append( [nums[i]] + x)
else:
output.append ([nums[i]] + result)
#print output, nums
return output