【问题标题】:Adding Results of Recursion to An ArrayList将递归结果添加到 ArrayList
【发布时间】:2015-03-01 23:10:04
【问题描述】:

我正在尝试查找单词的所有排列并将其添加到 Arraylist 并返回数组列表。但是,我相信我的递归是正确的,但是将结果添加到 ArrayList 时存在问题。这就是我目前所拥有的。我传递的参数是“吃”和“”,返回的是“茶”3次

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

【问题讨论】:

  • 递归调用的结果存储在哪里? permutations(word, blah, temp);
  • 你有另一种采用 3 个参数的排列方法吗?
  • permutations() 有 2 个参数,你用 3 个参数调用它。还有其他函数吗?
  • 另外,我认为不需要这个 for 循环,因为递归方法无论如何都会经历整个事情......
  • @issathink 哎呀,我只是想将 Arraylist 作为参数传递,但是,这似乎更糟糕,所以我把它改回来了。我只是忘了把它全部改回来,但结果还是一样

标签: java arrays recursion arraylist permutation


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2010-12-13
    相关资源
    最近更新 更多