递归打印字符串的所有排列(Javascript) [英] Recursively print all permutations of a string (Javascript)

查看:180
本文介绍了递归打印字符串的所有排列(Javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了其他语言的这个问题的版本,但不是JS。

I've seen versions of this question for other languages, but not for JS.

是否可以在一个函数中递归执行此操作?

Is it possible to do this recursively in one function?

我知道我需要取字符串中的第一个元素,然后将其附加到每个解决方案中,以便对字符串的其余部分进行递归。
从逻辑上讲,我理解递归是如何进行的。我只是不明白如何将第一个字符串附加到每个递归解决方案上

I understand that I need to take the first element in the string, and then append it to each solution to the recursion on the remainder of the string. So logically, I understand how the recursion needs to go. I just don't understand how to append the first char onto each of the recursive solutions

var myString = "xyz";

function printPermut(inputString){
    var outputString;
    if(inputString.length === 0){
        return inputString;
    }
    if(inputString.length === 1){
        return inputString;
    }
    else{
       for(int i = 0; i<inputString.length(); i++){
           //something here like: 
           //outputString = outputString.concat(printPermut(inputString.slice(1))??
           //maybe store each unique permutation to an array or something?
       } 
    }
}


推荐答案

让我们编写一个函数,返回字符串的所有排列作为由于你不想要任何全局变量,所以返回排列是至关重要的。

Let's write a function that returns all permutations of a string as an array. As you don't want any global variables, returning the permutations is crucial.

function permut(string) {
    if (string.length < 2) return string; // This is our break condition

    var permutations = []; // This array will hold our permutations

    for (var i=0; i<string.length; i++) {
        var char = string[i];

        // Cause we don't want any duplicates:
        if (string.indexOf(char) != i) // if char was used already
            continue;           // skip it this time

        var remainingString = string.slice(0,i) + string.slice(i+1,string.length); //Note: you can concat Strings via '+' in JS

        for (var subPermutation of permut(remainingString))
            permutations.push(char + subPermutation)

    }
    return permutations;
}

要打印它们,之后只需迭代数组:

To print them, just iterate over the array afterwards:

var myString = "xyz";
permutations = permut(myString);
for (permutation of permutations)
    print(permutation) //Use the output method of your choice

希望我能帮你解决问题。

Hope I could help you with your question.

这篇关于递归打印字符串的所有排列(Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆