forked from mgechev/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations.js
More file actions
44 lines (38 loc) · 1 KB
/
Copy pathpermutations.js
File metadata and controls
44 lines (38 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
(function (exports) {
'use strict';
var permutations = (function () {
var res;
function swap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* Finds all the permutations of given array.
* Complexity O(n*n!).
*
* @param {Array} arr Array to find the permutations of
* @param {Number} current Current element
* @returns {Array} Array containing all the permutations
*/
function permutations(arr, current) {
if (current >= arr.length) {
return res.push(arr.slice());
}
for (var i = current; i < arr.length; i += 1) {
swap(arr, i, current);
permutations(arr, current + 1);
swap(arr, i, current);
}
}
return function (arr) {
res = [];
permutations(arr, 0);
var temp = res;
// Free the extra memory
res = null;
return temp;
};
}());
exports.permutations = permutations;
}(typeof exports === 'undefined' ? window : exports));