//====================================================
function getPermutations(str){
//Enclosed data to be used by the internal recursive function permutate():
var permutations = [], //generated permutations stored here
nextWord = [], //next word builds up in here
chars = [] //collection for each recursion level
;
//---------------------
//split words or numbers into an array of characters
if (typeof str === 'string') chars = str.split('');
else if (typeof str === 'number') {
str = str + ""; //convert number to string
chars = str.split('');//convert string into char array
}
//============TWO Declaratives========
permutate(chars);
return permutations;
//===========UNDER THE HOOD===========
function permutate(chars){ //recursive: generates the permutations
if(chars.length === 0)permutations.push(nextWord.join(''));
for (var i=0; i < chars.length; i++){
chars.push(chars.shift()); //rotate the characters
nextWord.push(chars[0]); //use the first char in the array
permutate(chars.slice(1)); //Recurse: array-less-one-char
nextWord.pop(); //clear for nextWord (multiple pops)
}
}
//--------------------------------
}//==============END of getPermutations(str)=============
nextWord.pop()如何被多次调用?
不会排列(chars.slice(1));不让nextWord.pop()执行,因为它将带您回到排列函数的顶部?
另外,当chars变为空时,无法对其调用slice进行permutate(chars.slice(1));谁再次填充字符? char由nextWord.pop()填充吗?因为pop正在将值返回到permutate函数?
在chrome调试器中单步执行此代码尚不清楚。
最佳答案
递归调用permutate
处于循环内,每次执行时,都会将其放入调用堆栈中。多次调用nextWord.pop
以完成堆栈上每个递归调用的执行。您可以使用此工具http://visualgo.net/recursion.html可视化递归。如果您拥有Webstorm之类的工具,则可以在调试器中运行该工具,以查看第一次调用nextWord.pop
时在堆栈中有三个permutate()调用。
关于javascript - 生成字符串排列的递归函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32900592/