Skip to content

Commit 878405f

Browse files
committed
46. Permutations
1 parent 8329c51 commit 878405f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Backtracking/permute.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Given an array nums of distinct integers, return all the possible
2+
# permutations
3+
# . You can return the answer in any order.
4+
5+
6+
7+
# Example 1:
8+
9+
# Input: nums = [1,2,3]
10+
# Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
11+
# Example 2:
12+
13+
# Input: nums = [0,1]
14+
# Output: [[0,1],[1,0]]
15+
# Example 3:
16+
17+
# Input: nums = [1]
18+
# Output: [[1]]
19+
20+
21+
# Constraints:
22+
23+
# 1 <= nums.length <= 6
24+
# -10 <= nums[i] <= 10
25+
# All the integers of nums are unique.
26+
27+
28+
from typing import List
29+
class Solution:
30+
def permute(self, nums: List[int]) -> List[List[int]]:
31+
ans = []
32+
chk = [False]*len(nums)
33+
34+
def dfs(path):
35+
if len(nums) == len(path):
36+
return ans.append(path.copy())
37+
for i, n in enumerate(nums):
38+
if chk[i]:
39+
continue
40+
chk[i] = True
41+
path.append(n)
42+
dfs(path)
43+
path.pop()
44+
chk[i] = False
45+
dfs([])
46+
return ans

0 commit comments

Comments
 (0)