47. Permutations II
https://leetcode.com/problems/permutations-ii/
Python
Use Python itertools.permutations
from itertools import permutations
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
return set([perm for perm in permutations(nums)])
Backtracking
from itertools import permutations
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
result = set()
def backtracking(track: list, used: set):
if len(track) == len(nums):
result.add(tuple(track))
return
for i, num in enumerate(nums):
if i in used:
continue
used.add(i)
track.append(num)
backtracking(track, used)
used.remove(i)
track.pop()
backtracking([], set())
return result
Javascript
var permuteUnique = function(nums) {
const result = [];
var backtrack = function(hashmap, record =[]) {
// base case: the length of array has reached the length of nums
if (record.length === nums.length) {
result.push(record.slice());
return;
}
// use hashmap to memorize the number which had traversed
for (let key in hashmap) {
if (hashmap[key] <= 0) continue;
hashmap[key] -= 1;
record.push(Number(key));
backtrack(hashmap, record);
hashmap[key] += 1;
record.pop();
}
}
const hashmap = nums.reduce((acc, num) => {
if (acc[num] !== undefined) acc[num] += 1;
else acc[num] = 1;
return acc;
}, {})
backtrack(hashmap)
return result;
};