gpt4 book ai didi

java - 如何生成不同大小元素的排列

转载 作者:行者123 更新时间:2023-12-01 22:42:14 24 4
gpt4 key购买 nike

我有一组元素作为输入,我们假设它们是字符串:

String[] elements = {"A","B","C","D"};

我想生成大小为 1、2 和 3(直到 n-1)元素的所有排列,而不重复任何元素。

因此输出将如下所示:

A
B
C
D
AB
AC
AD
BC
BD
CD
ABC
ABD
ACD
BCD

当前代码我已生成所有排列,但有重复:(

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

public static void main()
{
String[] elements = {"A","B","C","D"};
for(int i=1; i<=elements.length; i++)
{
String[] result = getAllLists(elements, i);
for(int j=0; j<result.length; j++)
{
System.out.println(result[j]);
}
}
}

最佳答案

快速而肮脏的关键是按字典顺序构造新字符串...... token 包含A、B、C、D开始时结果还包含 A、B、C、D

运行后显示的输出

结果 = perm( token ,结果,1,3);

 public static List<String> perm(List<String> tokens, List<String> result, int currentLength, int maxLength){
if(currentLength == maxLength){
return result;
}
List<String> gen = new ArrayList<String>();
for(String s : result){
for(String s1 : tokens){
if(s.equals(s1) || s.contains(s1)){
continue;
}else{
String temp = s+s1;
char[] ca = temp.toCharArray();
Arrays.sort(ca);
String res = "";
for(char c : ca){
res+=c;
}
if(gen.contains(res)){
continue;
}
gen.add(res);
}
}
}
if(gen.size() > 0){
result.addAll(perm(tokens,gen,currentLength+1,maxLength));
}
return result;
}

关于java - 如何生成不同大小元素的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25970176/

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