算法的复杂性是O(NxMxK …. xZ),如果我错了,我不知道它是否是一种“有效的方式”….我用它作为一种回溯解决方案
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ProductEnums {
public enum EnumOne {
One,
OneMore;
}
public enum EnumTwo {
Two,
}
public enum EnumThree {
Three,
ThreeMore;
}
public static void main(String[] args) {
// pass each values in enums
List a = product(EnumOne.values(),
EnumTwo.values(), EnumThree.values());
System.out.println(a);
}
public static List> product(Enum[]... enums) {
return product(new ArrayList<>(Arrays.asList(enums)));
}
public static List> product(List enums) {
if (enums.isEmpty()) {
//Trivial case of recursive function
return new ArrayList<>();
}
//remove first element
Enum[] myEnums = enums.remove(0);
List> out = new ArrayList<>();
for (Enum e : myEnums) {
//call recursive
List> list = product(enums);
for (List list_enum : list) {
//for each list get from recursion adding element e
list_enum.add(0, e);
out.add(list_enum);
}
if(list.isEmpty()){
List list_enum = new ArrayList<>();
list_enum.add(e);
out.add(list_enum);
}
}
enums.add(0, myEnums); //Backtraking
return out;
}
}
结果
[[One, Two, Three], [One, Two, ThreeMore], [OneMore, Two, Three], [OneMore, Two, ThreeMore]]