将递归结果添加到ArrayList

时间:2015-03-01 23:10:04

标签: java arrays recursion arraylist permutation

我正在尝试查找单词的所有排列并将其添加到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;
}

1 个答案:

答案 0 :(得分:1)

可能我没有正确的想法,你的方法找到一个简单的解决方案,当我开始工作时,我最终得到了这个。我希望这不是太多的离开,它仍然有用。输出是:

  

[茶,tae,eta,吃,吃,吃]

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