Skip to content

Commit d378180

Browse files
authored
Merge pull request #131 from jeantimex/permutations
feat(backtracking): Permutations
2 parents 050b96a + 71ec53b commit d378180

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

README.md

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

113114
### Linked List
114115

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { assert } from 'chai';
2+
import permute from '../permutations';
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', () => {
12+
const testCases = [[[1, 2, 3], [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]]];
13+
14+
testCases.forEach((testCase, index) => {
15+
it(`should get the permutations using back tracking ${index}`, () => {
16+
const nums = testCase[0];
17+
const expected = testCase[1];
18+
const actual = permute(nums);
19+
assert(actual.sort(sorter), expected.sort(sorter));
20+
});
21+
});
22+
});

src/backtracking/permutations.js

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

0 commit comments

Comments
 (0)