【发布时间】:2017-01-17 14:34:20
【问题描述】:
我有一个任务是根据堆的算法排列来计算重复的字符串。我要做的第一件事是输出交换的字符串,我从jake's answer 找到了这段代码,有人可以帮我理解这段代码中的递归吗一个循环?该函数的输出是交换后的字符串。
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 个字符的编辑中。
标签: javascript algorithm recursion heaps-algorithm