-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path46_Permutations.py
More file actions
51 lines (48 loc) · 1.36 KB
/
46_Permutations.py
File metadata and controls
51 lines (48 loc) · 1.36 KB
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
48
49
50
51
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def helper(start, end, nums):
if(start == end-1):
res.append(list(nums))
for k in range(start, end):
nums[start], nums[k] = nums[k], nums[start]
helper(start+1, end, nums)
nums[start], nums[k] = nums[k], nums[start]
res = []
helper(0, len(nums), nums)
return res
def permute_iter(self, num):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not num:
return []
ret = [[]]
for n in num:
tmp_ret = []
l = len(ret[-1])
for seq in ret:
for i in range(l, -1, -1):
tmp_ret.append(seq[:i] + [n] + seq[i:])
ret = tmp_ret
return ret
def permute_iter2(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return []
ret = [[]]
for n in nums:
tmp = []
l = len(ret[0])
for sq in ret:
for i in range(0, l+1):
tmp.append(sq[:i]+[n]+sq[i:])
ret = tmp
return ret