Java anagram recursion List <list <string>&gt;仅存储空列表<strings> </strings> </list <string>

时间:2012-11-02 22:51:10

标签: java recursion

嗨在这个递归方法中,我试图找到所有字谜并将其添加到List&gt;但是当我运行这段代码时会发生什么呢?它只会返回很多空列表。

      private List<List<String>> findAnagrams(LetterInventory words,
        ArrayList<String> anagram, int max,
        Map<String, LetterInventory> smallDict, int level, List<List<String>> result) {

    ArrayList<String> solvedWord = new ArrayList<String>();
    LetterInventory shell;
    LetterInventory shell2;
    if (level < max || max == 0) {
        Iterator<String> it = smallDict.keySet().iterator();
        while (it.hasNext()) {
            String k = it.next();
            shell = new LetterInventory(k);
            shell2 = words;
            if (shell2.subtract(shell) != null) {
                anagram.add(k);
                shell2 = words.subtract(shell);
                if (shell2.isEmpty()) {
                    //System.out.println(anagram.toString()); it prints off fine here
                                            result.add(anagram); // but doesnt add here

                }
                else 

                    findAnagrams(shell2, anagram, max, smallDict, level + 1, result);
                anagram.remove(anagram.size()-1);
            }
        }
    }
    return results;
}

1 个答案:

答案 0 :(得分:2)

我的猜测就在这里。

else 
    findAnagrams(shell2, anagram, max, smallDict, level + 1, result);
anagram.remove(anagram.size()-1);  // this is outside of the else case

每次添加元素时都会从anagram中删除元素。你的意思是它在else吗?

else {
    findAnagrams(shell2, anagram, max, smallDict, level + 1, result);
    anagram.remove(anagram.size()-1);
}