JavaScript实现穷举排列(permutation)算法谜题解答_javascript技巧
程序员文章站
2022-05-17 11:53:45
...
谜题
/**
* Created by cshao on 12/23/14.
*/
[ [ 'a', 'b', 'c' ],
[ 'a', 'c', 'b' ],
[ 'b', 'a', 'c' ],
[ 'b', 'c', 'a' ],
[ 'c', 'a', 'b' ],
[ 'c', 'b', 'a' ] ]
穷举一个数组中各个元素的排列
策略
减而治之、递归
JavaScript解
复制代码 代码如下:
/**
* Created by cshao on 12/23/14.
*/
function getPermutation(arr) {
if (arr.length == 1) {
return [arr];
}
var permutation = [];
for (var i=0; i
var arrClone = arr.slice(0);
arrClone.splice(i, 1);
var childPermutation = getPermutation(arrClone);
for (var j=0; j
}
permutation = permutation.concat(childPermutation);
}
return permutation;
}
var permutation = getPermutation(['a','b','c']);
console.dir(permutation);
结果
复制代码 代码如下:
[ [ 'a', 'b', 'c' ],
[ 'a', 'c', 'b' ],
[ 'b', 'a', 'c' ],
[ 'b', 'c', 'a' ],
[ 'c', 'a', 'b' ],
[ 'c', 'b', 'a' ] ]
推荐阅读
-
JavaScript实现穷举排列(permutation)算法谜题解答_javascript技巧
-
JavaScript实现穷举排列(permutation)算法谜题解答_javascript技巧
-
JS实现的数组全排列输出算法_javascript技巧
-
JavaScript实现N皇后问题算法谜题解答_javascript技巧
-
JavaScript全排列的六种算法 具体实现_javascript技巧
-
JavaScript实现N皇后问题算法谜题解答_javascript技巧
-
JavaScript全排列的六种算法 具体实现_javascript技巧
-
JavaScript实现三阶幻方算法谜题解答_javascript技巧
-
JavaScript实现三阶幻方算法谜题解答_javascript技巧