gpt4 book ai didi

java - 字符数组的每一个组合

转载 作者:行者123 更新时间:2023-11-29 10:19:25 25 4
gpt4 key购买 nike

在不重复字母的情况下尝试显示数组字符的每个组合时遇到问题。

public static String[] getAllLists(String[] elements, int lengthOfList)
{
//initialize our returned list with the number of elements calculated above
String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];

//lists of length 1 are just the original elements
if(lengthOfList == 1) return elements;
else
{
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);

//append the sublists to each element
int arrayIndex = 0;

for(int i = 0; i < elements.length; i++)
{
for(int j = 0; j < allSublists.length; j++)
{
//add the newly appended combination to the list
allLists[arrayIndex] = elements[i] + allSublists[j];
arrayIndex++;
}
}

return allLists;
}
}

上面的代码完美无缺,但是每个字母都使用了不止一次,这在这种情况下是做不到的。

我现在不知道该怎么做。

最佳答案

这是一个示例实现。本质上它接受一个 String 并遍历每个字符,将那个字符放在前面。然后它在剩余的字符上递归。该结构消除了重复字母的问题,因为递归的输入已经删除了您已经使用过的字符。

我还将结果存储在一个集合中以删除语义等价物。输入“aab”可以切换 char 0 和 char 1,但仍然是“aab”。我使用 TreeSet 来保留顺序以便更轻松地验证输出,但 HashSet 会更快。

  public static Set<String> permute(String chars)
{
// Use sets to eliminate semantic duplicates (aab is still aab even if you switch the two 'a's)
// Switch to HashSet for better performance
Set<String> set = new TreeSet<String>();

// Termination condition: only 1 permutation for a string of length 1
if (chars.length() == 1)
{
set.add(chars);
}
else
{
// Give each character a chance to be the first in the permuted string
for (int i=0; i<chars.length(); i++)
{
// Remove the character at index i from the string
String pre = chars.substring(0, i);
String post = chars.substring(i+1);
String remaining = pre+post;

// Recurse to find all the permutations of the remaining chars
for (String permutation : permute(remaining))
{
// Concatenate the first character with the permutations of the remaining chars
set.add(chars.charAt(i) + permutation);
}
}
}
return set;
}

运行示例:

  public static void main(String[] args)
{
for (String s : CharPermuter.permute("abca"))
{
System.out.println(s);
}
}

生成:

aabc
aacb
abac
abca
acab
acba
baac
baca
bcaa
caab
caba
cbaa

关于java - 字符数组的每一个组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9666903/

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