gpt4 book ai didi

java - 将递归结果添加到 ArrayList

转载 作者:行者123 更新时间:2023-12-01 11:51:24 25 4
gpt4 key购买 nike

我试图找到一个单词的所有排列并将其添加到数组列表中并返回数组列表。但是,我相信我的递归是正确的,但是将结果添加到 ArrayList 时存在问题。这就是我到目前为止所拥有的。我传递的参数是“eat”和“”,返回的是3次“tea”

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

最佳答案

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

[tea, tae, eta, eat, ate, 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com