我试图找到一个单词的所有排列并将其添加到Arraylist中并返回数组列表。但是,我相信我的递归是正确的,但是将结果添加到ArrayList还是有问题的。我传递的参数是“吃”和“”,返回的是“茶”三遍

public static ArrayList<String> permutations(String word, String beginning)
{
    int l = word.length();
    ArrayList<String> temp = new ArrayList<String>();

    if(l == 0)
        temp.add(beginning + word);
    else
    {
        char c = word.charAt(l-1);
        String blah = (beginning + c);
        word = word.substring(0, l-1);
        for(int i = 0; i < l; i++)
        {
            permutations(word, blah);
            temp.add(blah + word);
        }

    }
    return temp;
}

最佳答案

可能我对您找到一个简单解决方案的方法没有正确的想法,等到我开始工作时,我就结束了。我希望这不是一个太大的偏离,它仍然会有所帮助。输出为:


[茶,泰,埃塔,吃,吃,Aet]


import java.util.ArrayList;

public class Perm {
    public static void main(String[] args) {
        ArrayList<String> perms = new ArrayList<String>();
        permutations("tea", perms);
        System.out.println(perms);
    }

    public static ArrayList<String> permutations(String word, ArrayList<String> perms)
    {
        int l = word.length();

        // If the word has only a single character, there is only
        // one permutation -- itself. So we add it to the list and return
        if (l == 1) {
            perms.add(word);
            return perms;
        }

        // The word has more than one character.
        // For each character in the word, make it the "beginning"
        // and prepend it to all the permutations of the remaining
        // characters found by calling this method recursively

        for (int i=0; i<word.length(); ++i) {
            char beginning = word.charAt(i);

            // Create the remaining characters from everything before
            // and everything after (but not including) the beginning char
            String blah = word.substring(0,i)+word.substring(i+1);

            // Get all the permutations of the remaining characters
            // by calling recursively
            ArrayList<String> tempArray = new ArrayList<String>();
            permutations(blah, tempArray);

            // Prepend the beginning character to each permutation and
            // add to the list
            for (String s : tempArray) {
                perms.add(beginning + s);
            }
        }

        return perms;
    }
}

关于java - 将递归结果添加到ArrayList,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28800393/

10-10 23:59