简体   繁体   English

递归解决方案:字符串排列。 无法在JavaScript中返回排列字符串数组

[英]Recursive solution : string permutation. Unable to return array of permutation strings in javascript

Here is my js:- 这是我的js:-

function recPerm(rest, soFar) { 
    var next;
    var remaining;
    var output=[];
    if (rest === '') {
        console.log(soFar); //outputting strings..and this works
        output.push(soFar); 
    } else {

        for (var i = 0; i < rest.length; i++) {
            remaining = rest.substr(0,i) + rest.substr(i+1,rest.length-1);
            next = soFar + rest[i];
            recPerm(remaining, next);
        }

    }
    return output; //returns an empty array in the end
}

var out=recPerm('abc',''); 
console.log(out);  //prints empty array

Recursively, I am trying to print permutations of an input string. 递归地,我试图打印输入字符串的排列。 I am passing the input string and a blank string which recursively then calls this function with remaining string and next individual char in string to be considered. 我传递了输入字符串和一个空白字符串,然后递归地调用了此函数,并使用剩下的字符串和要考虑的字符串中的下一个单独字符。 Inside base case, I am succesfully able to log individual strings . 在基本情况下,我能够成功记录单个字符串。 But somehow its not saving it in my array towards the end. 但是某种程度上,它并没有将其保存到我的数组中。 Is there something i am missing out in my JS? 我的JS中缺少什么吗?

Your problem resides on the output variable, that is private to the recPerm function and when you recursively call recPerm , of course, it will be recreated... I suggest You to pass that variable as parameter: 您的问题outputrecPerm函数私有的output变量上,并且当您递归调用recPerm ,当然会重新创建它。我建议您将该变量作为参数传递:

 function recPerm(rest, soFar, output) { var next; var remaining; output = Array.isArray(output) ? output : []; if(rest === '') { output.push(soFar); } else { for (var i = 0; i < rest.length; i++) { remaining = rest.substr(0,i) + rest.substr(i+1,rest.length-1); next = soFar + rest[i]; recPerm(remaining, next, output); } } return output; //returns an empty array in the end } var out=recPerm('abc',''); console.log(out); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM