Skip to content

Commit fa02e4a

Browse files
committed
feat(backtracking): Permutations II
1 parent d378180 commit fa02e4a

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
110110
- [Combination Sum II](src/backtracking/combination-sum-ii.js)
111111
- [Combination Sum III](src/backtracking/combination-sum-iii.js)
112112
- [Permutations](src/backtracking/permutations.js)
113+
- [Permutations II](src/backtracking/permutations-ii.js)
113114

114115
### Linked List
115116

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { assert } from 'chai';
2+
import permuteUnique from '../permutations-ii';
3+
4+
const sorter = (a, b) => {
5+
if (a.length === b.length) {
6+
return a.toString().localeCompare(b.toString());
7+
}
8+
return a.length - b.length;
9+
};
10+
11+
describe('Permutations II', () => {
12+
const testCases = [
13+
[[1, 2, 3], [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]],
14+
[[1, 1, 2], [[1, 1, 2], [1, 2, 1], [2, 1, 1]]],
15+
];
16+
17+
testCases.forEach((testCase, index) => {
18+
it(`should get the permutations using back tracking ${index}`, () => {
19+
const nums = testCase[0];
20+
const expected = testCase[1];
21+
const actual = permuteUnique(nums);
22+
assert(actual.sort(sorter), expected.sort(sorter));
23+
});
24+
});
25+
});

src/backtracking/permutations-ii.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Permutations II
3+
*
4+
* Given a collection of numbers that might contain duplicates, return all possible unique permutations.
5+
*
6+
* For example,
7+
* [1,1,2] have the following unique permutations:
8+
* [
9+
* [1,1,2],
10+
* [1,2,1],
11+
* [2,1,1]
12+
* ]
13+
*/
14+
15+
/**
16+
* @param {number[]} nums
17+
* @return {number[][]}
18+
*/
19+
const permuteUnique = nums => {
20+
const results = [];
21+
nums.sort((a, b) => a - b);
22+
backtracking(nums, {}, [], results);
23+
return results;
24+
};
25+
26+
const backtracking = (nums, used, solution, results) => {
27+
if (solution.length === nums.length) {
28+
results.push(solution.slice());
29+
return;
30+
}
31+
32+
for (let i = 0; i < nums.length; i++) {
33+
if (used[i] || (i > 0 && nums[i] === nums[i - 1] && !used[i - 1])) {
34+
continue;
35+
}
36+
37+
solution.push(nums[i]);
38+
used[i] = true;
39+
backtracking(nums, used, solution, results);
40+
solution.pop();
41+
used[i] = false;
42+
}
43+
};
44+
45+
export default permuteUnique;

0 commit comments

Comments
 (0)