-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20permutation.js
40 lines (36 loc) · 1.01 KB
/
20permutation.js
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
function permutations(str){
var arr = str.split(''),
len = arr.length,
perms = [],
rest,
picked,
restPerms,
next;
if (len == 0)
return [str];
for (var i=0; i<len; i++)
{
rest = Object.create(arr);
picked = rest.splice(i, 1);
restPerms = permutations(rest.join(''));
for (var j=0, jLen = restPerms.length; j< jLen; j++)
{
next = picked.concat(restPerms[j]);
perms.push(next.join(''));
}
}
return perms;
}
module.exports = permutations;
/*
console.log(permutations('abc'))
[ 'abc', 'acb', 'bac', 'bca', 'cab', 'cba' ]
console.log(permutations('htg'))
[ 'htg', 'hgt', 'thg', 'tgh', 'ght', 'gth' ]
console.log(permutations('ret'))
[ 'ret', 'rte', 'ert', 'etr', 'tre', 'ter' ]
console.log(permutations('gtr'))
[ 'gtr', 'grt', 'tgr', 'trg', 'rgt', 'rtg' ]
console.log(permutations('ju'))
[ 'ju', 'uj' ]
*/