我们需要编写一个执行以下操作的函数-
将整数数组作为参数(例如[1,2,3,4])
创建[1,2,3,4]的所有可能排列的数组,每个排列的长度为4(即原始数组的长度)
为此的代码将是-
const arr = [1, 2, 3, 4]; const permute = (arr = [], res = [], used = []) => { let i, ch; for (i = 0; i < arr.length; i++) { ch = arr.splice(i, 1)[0]; used.push(ch); if (arr.length === 0) { res.push(used.slice()); } permute(arr, res, used); arr.splice(i, 0, ch); used.pop(); }; return res; }; console.log(permute(arr));
输出结果
控制台中的输出将是-
[ [ 1, 2, 3, 4 ], [ 1, 2, 4, 3 ], [ 1, 3, 2, 4 ], [ 1, 3, 4, 2 ], [ 1, 4, 2, 3 ], [ 1, 4, 3, 2 ], [ 2, 1, 3, 4 ], [ 2, 1, 4, 3 ], [ 2, 3, 1, 4 ], [ 2, 3, 4, 1 ], [ 2, 4, 1, 3 ], [ 2, 4, 3, 1 ], [ 3, 1, 2, 4 ], [ 3, 1, 4, 2 ], [ 3, 2, 1, 4 ], [ 3, 2, 4, 1 ], [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ], [ 4, 1, 2, 3 ], [ 4, 1, 3, 2 ], [ 4, 2, 1, 3 ], [ 4, 2, 3, 1 ], [ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ] ]