我正在使用堆算法,它与output
记录结果的回调函数控制台配合得很好。但是,如果我将回调函数的操作更改output
为array.push
,它会一遍又一遍地推送同一个数组。我究竟做错了什么?
let swap = function (array, index1, index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
return array;
};
let permutationHeap = function (array, callback, n) {
n = n || array.length;
if (n === 1) {
callback(array);
} else {
for (var i = 1; i <= n; i++) {
permutationHeap(array, callback, n - 1);
if (n % 2) {
swap(array, 0, n - 1);
} else {
swap(array, i - 1, n - 1);
}
}
}
};
let finalResult = [];
var output = function (input) {
//console.log(input);
finalResult.push(input);
};
permutationHeap(["Mary", "John", "Denis"], output);
console.log(finalResult)