Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit b45094f

Browse files
committedJan 16, 2023
Add solution #47
1 parent b5cede9 commit b45094f

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard|
5050
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|
5151
46|[Permutations](./0046-permutations.js)|Medium|
52+
47|[Permutations II](./0047-permutations-ii.js)|Medium|
5253
48|[Rotate Image](./0048-rotate-image.js)|Medium|
5354
49|[Group Anagrams](./0049-group-anagrams.js)|Medium|
5455
50|[Pow(x, n)](./0050-powx-n.js)|Medium|

‎solutions/0047-permutations-ii.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 47. Permutations II
3+
* https://leetcode.com/problems/permutations-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given a collection of numbers, nums, that might contain duplicates,
7+
* return all possible unique permutations in any order.
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @return {number[][]}
13+
*/
14+
var permuteUnique = function(nums) {
15+
const result = new Set();
16+
backtrack(result, nums);
17+
return Array.from(result).map(s => s.split(','));
18+
};
19+
20+
function backtrack(result, nums, order = []) {
21+
if (!nums.length) {
22+
result.add(order.join());
23+
} else {
24+
for (let i = 0; i < nums.length; i++) {
25+
backtrack(
26+
result,
27+
[...nums.slice(0, i), ...nums.slice(i + 1)],
28+
[...order, nums[i]],
29+
);
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)
Please sign in to comment.