将递归结果添加到ArrayList



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

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;
}

可能我对你的方法没有正确的想法来找到一个简单的解决方案,当我把事情做好的时候,我最终得到了这个。我希望这不是一个太大的偏离,它仍然有帮助。输出为:

[茶,tae,eta,吃,吃,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;
    }
}

最新更新