[英]java generate powerset permutations from grouped elements
我有一組N組,每組包含可變數量的元素。 我想要一個函數,它將返回所有元素的所有可能的排列(長度為1到N),其中每個組中只有一個元素可以出現在任何排列中。
例如,考慮2組{A, B}
和{C, D, E}
然后我想返回以下列表:
{A}, {B}, {C}, {D}, {E},
{AC}, {AD}, {AE}, {BC}, {BD}, {BE}, {CA}, {CB}, {DA}, {DB}, {EA}, {EB}
我嘗試編寫一個遞歸函數,但我似乎無法使它工作......這就是我到目前為止所擁有的。 任何幫助它的工作將非常感激。
public class Test {
public static void main(String[] args) {
List<String> g1 = new ArrayList<String>();
g1.add("a");
g1.add("b");
List<String> g2 = new ArrayList<String>();
g2.add("c");
g2.add("d");
g2.add("e");
List<List<String>> groups = new ArrayList<List<String>>();
groups.add(g1);
groups.add(g2);
int size = 2;
List<List<String>> perms = generatePermutations(groups, size);
System.out.println(perms.size());
}
private static List<List<String>> generatePermutations(List<List<String>> groups, int size) {
List<List<String>> permutations = new ArrayList<List<String>>();
if ( groups.size() == 0 ) {
return permutations;
}
int n = groups.size();
for ( int i=0; i<n; i++ ) {
List<List<String>> otherGroups = new ArrayList<List<String>>(groups);
otherGroups.remove(i);
for ( int j=0; j<groups.get(i).size(); j++ ) {
String aKey = groups.get(i).get(j);
for ( List<String> subPerm : generatePermutations(otherGroups, size - 1) ) {
List<String> newList = new ArrayList<String>();
newList.add(aKey);
newList.addAll(subPerm);
permutations.add(newList);
}
}
}
return permutations;
}
}
當我必須解決這些問題時,我總是嘗試將它們分成較小的任務,每個任務導致一個不同的方法調用,而不是從一開始就使用許多內部循環。
我會做這樣的事情
public class Main {
public static void main(String[] args) {
char[] x={'A','B'},y={'C','D','E'},z={'F','G','H','I'};
char[][]group={x,y,z};
perm(group);
}
static void perm(char[][]g){
// Reorganize "g" changing the order of the components (x, y and z in this case)
// in all possible ways and call perm2().
// Here you perform the "upper level" permutation between sets.
// In this case it will result in 6 calls
perm2(g);
}
static void perm2(char[][]g){
// perform a "lower level" permutation on the given order of x, y, z
}
}
這更容易測試和驗證。 最終,當您找到解決方案時,您可以考慮使用多個內部循環在一個方法中“壓縮”解決方案。
希望能幫助到你!
也許我誤解了這個問題...但我認為這個問題有點復雜。 我想幫忙,但我需要更好地理解問題。 如果我理解得當你需要:
找到作為輸入給出的'集合'的powerset:
{A,B} {C,D,E} --> {} {A,B} {C,D,E} {{A,B},{C,D,E}}
然后,計算powerset每個成員的笛卡爾積:
{} {A,B} {C,D,E} {{A,B},{C,D,E}} --> {} {A,B} {C,D,E} {AC,AD,AE,BC,BD,BE}
然后計算獲得的集合內容的排列:
{} {A,B} {C,D,E} {AC,AD,AE,BC,BD,BE} --> {} {A,B} {C,D,E} {AC,AD,AE,BC,BD,BE,CA,DA,EA,CB,DB,EB}
最后,所有集合將在一個集合中“展平”:
{A,B,C,D,EAC,AD,AE,BC,BD,BE,CA,DA,EA,CB,DB,EB}
是這樣嗎? 有一些方法可以遞歸地計算powerset,笛卡爾積和置換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.