-
Notifications
You must be signed in to change notification settings - Fork 0
/
0046_perm.py
87 lines (68 loc) · 2.05 KB
/
0046_perm.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#https://leetcode.com/problems/permutations/submissions/
"""
Runtime: 60 ms, faster than 51.19% of Python3 online submissions for Permutations.
Memory Usage: 14.1 MB, less than 21.82% of Python3 online submissions for Permutations.
"""
def permute0(nums):
nums = set(nums)
r = []
def dfs(visited, n, acc):
if n not in visited:
acc2 = acc.copy()
acc2.append(n)
visited = visited.copy()
visited.add(n)
if len(visited) == len(nums) + 1:
r.append(acc2[1:])
for ele in nums - visited:
dfs(visited, ele, acc2)
dfs(set(), -100, [])
return r
"""
Runtime: 89 ms, faster than 6.43% of Python3 online submissions for Permutations.
Memory Usage: 14.3 MB, less than 21.82% of Python3 online submissions for Permutations.
"""
def permute1(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = set(nums)
r = []
def dfs(visited, n, acc):
if n not in visited:
acc2 = acc.copy()
acc2.append(n)
visited = visited.copy()
visited.add(n)
if len(visited) == len(nums):
r.append(acc2)
for ele in nums - visited:
dfs(visited, ele, acc2)
for i in nums:
dfs(set(), i, [])
return r
"""
Runtime: 86 ms, faster than 8.36% of Python3 online submissions for Permutations.
Memory Usage: 14.1 MB, less than 21.82% of Python3 online submissions for Permutations.
"""
def permute(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = set(nums)
r = []
def dfs(visited, n):
if n not in visited:
visited = visited.copy()
visited.append(n)
if len(visited) == len(nums):
r.append(visited)
for ele in nums - set(visited):
dfs(visited, ele)
for i in nums:
dfs([], i)
return r
print(permute([0, -1, 1]))
#print(permute([1, 2, 3]))