Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cba0db9

Browse files
Permutations
1 parent ebcad0b commit cba0db9

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

‎Backtracking/46-Permutations.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'''
2+
Permutations
3+
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
4+
5+
Example 1:
6+
7+
Input: nums = [1,2,3]
8+
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
9+
'''
10+
11+
12+
def permute(nums):
13+
result = []
14+
15+
# base case
16+
if len(nums) == 1:
17+
return [nums.copy()] #ornums[:] is a deep copy
18+
19+
for i in range(len(nums)):
20+
n = nums.pop()
21+
perms = permute(nums)
22+
23+
for perm in perms:
24+
perm.append(n)
25+
result.extend(perms)
26+
nums.append(n)
27+
return result
28+
29+
#T:O(2^n)
30+
#S:O(n)

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1010
- [x] [Letter Case Permutation](Backtracking/784-letter-case-permutation.py)
1111
- [x] [Subsets](Backtracking/78-Subsets.py)
1212
- [x] [Subsets-II](Backtracking/78-Subsets.py)
13+
- [x] [Permutations](Backtracking/46-Permutations.py)
1314

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /