考虑一个字符数组characterArray = {a,b,c,d}。我想创建一个列表,其中包含所有可能的元素组合作为Set。例如
Set 1 ={}
Set 2 = {a}
Set 3 = {b}
Set 4 = {c}
Set 5 = {a,b}
Set 6 ={a,c}
......
......
Set N = {a,b,c,d}
在生成上述所有可能的组合之后。我想将所有上面生成的集添加到列表(List)中。
以下是编写的示例代码
public class CreateSets {
char a[] = { 'a', 'b', 'c', 'd' };
List<HashSet> setList = new ArrayList<HashSet>();
public void createSubsets() {
for (int i = 0; i < a.length; i++) {
HashSet temp = new HashSet();
for (int j = i; j < a.length; j++) {
temp.add(a[j]);
}
setList.add(temp);
}
}
public static void main(String[] args) {
CreateSets cr = new CreateSets();
cr.createSubsets();
System.out.println(cr.setList);
}
}
答案 0 :(得分:1)
private List<HashSet<Character>> createSubsets(char[] a) {
List<HashSet<Character>> tempListList = new ArrayList<HashSet<Character>>();
if (a.length == 0) {
HashSet<Character> temp = new HashSet<Character>();
//temp.add(' ');
tempListList.add(temp);
return tempListList;
}
char tempChar = a[a.length-1];
List<HashSet<Character>> setList = createSubsets(Arrays.copyOf(a, a.length-1));
for (HashSet<Character> charSet : setList) {
HashSet<Character> tempSet = new HashSet<>(charSet);
tempSet.add(tempChar);
tempListList.add(tempSet);
}
setList.addAll(tempListList);
return setList;
}