From 1cdac98dc3f50e6d806638f857506a4a76bf457c Mon Sep 17 00:00:00 2001 From: Josue Kouka Date: Mon, 16 Jan 2023 18:19:21 -0800 Subject: [PATCH] Create 0047-permutations-ii.py --- python/0047-permutations-ii.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 python/0047-permutations-ii.py diff --git a/python/0047-permutations-ii.py b/python/0047-permutations-ii.py new file mode 100644 index 000000000..a97445344 --- /dev/null +++ b/python/0047-permutations-ii.py @@ -0,0 +1,25 @@ +import collections + + +class Solution: + + def permuteUnique(self, nums: List[int]) -> List[List[int]]: + result = [] + counter = collections.Counter(nums) + + def backtrack(perm, counter): + if len(perm) == len(nums): + result.append(perm.copy()) + + for n in counter: + if counter[n] == 0: + continue + perm.append(n) + counter[n] -= 1 + backtrack(perm, counter) + perm.pop() + counter[n] += 1 + + backtrack([], counter) + + return result