我有一個任務來計算基於堆的算法排列重複的字符串。我想要做的第一件事是輸出交換的字符串,我發現這個代碼jake's answer有人可以幫助我理解這個代碼循環內的遞歸嗎?這個函數的輸出是交換字符串。堆的算法排列JavaScript和遞歸堆棧?
function permAlone(string) {
var arr = string.split(''), // Turns the input string into a letter array.
permutations = []; // results
function swap(a, b) {
debugger; // This function will simply swap positions a and b inside the input array.
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
function gen(n) {
debugger;
if (n === 1) {
var x =arr.join('');
permutations.push(x);
} else {
for (var i = 0; i != n; i++) { // how does this loop executes within the call stack?
gen(n - 1);
debugger;
swap(n % 2 ? 0 : i, n - 1); // i don't understand this part. i understand the swap function, but I don't get how indexes are swapped here
}
}
}
gen(arr.length);
return permutations;
}
permAlone('xyz'); // output -> ["xyz","yxz","zxy","xzy","yzx","zyx"]
我一直在調試器上試驗它,但仍然無法得到所發生的事情。
請正確地在功能中縮進代碼。閱讀縮進代碼要容易得多。我自己試着編輯你的代碼,但是它不會將空格轉換爲編輯的最小6個字符。 –