-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0046-permutations.py
46 lines (39 loc) · 1.24 KB
/
0046-permutations.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
# time complexity: O(n*n!)
# space complexity: O(n)
from itertools import permutations
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def backtrack(curr: List[int]):
if len(curr) == len(nums):
result.append(curr[:])
for num in nums:
if num not in curr:
curr.append(num)
backtrack(curr)
curr.pop()
result = []
backtrack([])
return result
# class Solution:
# def permute(self, nums: List[int]) -> List[List[int]]:
# result = []
# for _, item in enumerate(list(permutations(nums))):
# result.append(list(item))
# return result
# class Solution:
# def permute(self, nums: List[int]) -> List[List[int]]:
# out = []
# stack = [[]]
# while stack:
# curr = stack.pop()
# if len(curr) == len(nums):
# out.append(curr)
# continue
# for num in nums:
# if num not in curr:
# stack.append((curr + [num]))
# print(out)
# return []
nums = [1, 2, 3]
print(Solution().permute(nums))