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 1350547

Browse files
Permutations II
1 parent 3e759f6 commit 1350547

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

‎Backtracking/47-Permutations-II.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'''Leetcode- https://leetcode.com/problems/permutations-ii/'''
2+
'''
3+
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
4+
5+
Example 1:
6+
7+
Input: nums = [1,1,2]
8+
Output:
9+
[[1,1,2],
10+
[1,2,1],
11+
[2,1,1]]
12+
'''
13+
14+
def permuteUnique(nums):
15+
result = []
16+
perms = []
17+
count = {n:0 for n in nums}
18+
for n in nums:
19+
count[n] += 1
20+
21+
def dfs():
22+
if len(perms) == len(nums):
23+
result.append(nums.copy())
24+
return
25+
26+
for n in count:
27+
if count[n] > 0:
28+
perms.append(n)
29+
count[n]-=1
30+
31+
dfs()
32+
33+
count[n] += 1
34+
perms.pop()
35+
36+
dfs()
37+
return result
38+
39+
print(permuteUnique([1,1,2])) #[[1, 1, 2], [1, 1, 2], [1, 1, 2]]
40+
41+
#T:O(n.2^n)
42+
#S:O(n)

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1111
- [x] [Subsets](Backtracking/78-Subsets.py)
1212
- [x] [Subsets-II](Backtracking/78-Subsets.py)
1313
- [x] [Permutations](Backtracking/46-Permutations.py)
14+
- [x] [Permutations II](Backtracking/47-Permutations-II.py)
1415

0 commit comments

Comments
(0)

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