【发布时间】:2017-01-21 18:31:35
【问题描述】:
我一直试图理解Heap's Algorithm,几天来,我仍然无法将其包裹在我的脑海中,循环内的递归代码感觉有些不对劲。这是 Wikipedia 上 Heap 算法中递归版本的 Javascript 版本。
function permAlone(string) {
var x = string.split(''); // Turns the input string into a letter array.
var arr = x; // this is global, I did this so i can see elements being swapped on swap function
function swap(a, b) { // This function will simply swap positions a and b inside the input array.
debugger;
var le = arr[a]; // element a
var lf = arr[b]; // element b
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
var yt = arr; // only did this to see updated elements on the array
}
var permutations = []; //output
function gen(length) {
if (length === 1) { // if true,
var x = arr.join('');
permutations.push(x); // push the updated joined' array
} else {
for (var i = 0; i < length; i++) { loop length = current elements
debugger;
gen(length - 1); // invoke recursion
swap(length % 2 ? 0 : i, length - 1); //invoke swap function. length % 2 ? 0 : i <- ternary test for the lengths' call stack. length -1 for the last element
}
}
}
gen(arr.length);
return permutations;
}
permAlone('abcd'); // this outputs to ["abcd", "bacd", "cabd", "acbd", "bcad", "cbad", "dbca", "bdca", "cdba", "dcba", "bcda", "cbda", "dacb", "adcb", "cdab", "dcab", "acdb", "cadb", "dabc", "adbc", "bdac", "dbac", "abdc", "badc"]
乍一看这段代码,我认为它是可以理解的,我理解它交换循环中的变量第 i 个值和最后一个元素,如果它是偶数,那么,如果它是奇数,它交换第一个和最后一个value.. 但是当我看到输出时,Recursion.. 不是重复太多了吗?谁能告诉我为什么?
【问题讨论】:
-
代码是你自己实现的还是在wiki页面上?我在您的 OP 中的链接上找不到代码 sn-p
-
你对算法背后的想法或递归有困难吗?
-
@shole,我提取了堆算法的部分,但它在这里link,
-
@JoelLee 我得到了算法,但没有得到循环中的递归部分,为什么它会以重复的方式重复出现? :(
-
好的,正在回答中。
标签: javascript algorithm loops recursion