考虑一组包含N个数字的数字S,我想要S的2个子集(S1,S2),使得S1 U S2 = S. S1交叉点S2 = null 。 我想要所有可能的S1和S2组合。 我知道,如果我的Set包含N个数字,我将获得2 ^ N个子集组合。 我试过以下代码。
DemoPartition Class
public class DemoPartition {
ArrayList nodes = new ArrayList();
ArrayList<Partitioning> partition = new ArrayList<>();
public static void main(String[] args) {
DemoPartition dp = new DemoPartition();
try {
int nums=3;
dp.DividePartition(dp.nodes,nums);
System.out.println(dp.partition);
System.out.println(dp.partition.size());
} catch (Exception e) {
e.printStackTrace();
}
}
private void DividePartition(ArrayList nodes,int nums) {
for (int i = 1; i <= nums; i++) {
nodes.add(i);
}
for (int i = 0; i < nodes.size(); i++) {
Partitioning parts = new Partitioning(new ArrayList(), new ArrayList());
parts.getMobile().add(nodes.get(i));
partition.add(parts);
}
ArrayList<Partitioning> temparray = new ArrayList<>();
for (Partitioning parts : partition) {
for (Object obj : nodes) {
if (!parts.getMobile().contains(obj)) {
parts.getCloud().add(obj);
}
}
if (nodes.size() != 2) {
Partitioning newone = new Partitioning(parts.getCloud(), parts.getMobile());
temparray.add(newone);
}
}
partition.addAll(temparray);
Partitioning parts = new Partitioning(new ArrayList(), new ArrayList());
for (int i = 0; i < nodes.size(); i++) {
parts.getMobile().add(nodes.get(i));
}
partition.add(parts);
Partitioning newone = new Partitioning(partition.get(partition.size() - 1).getCloud(), partition.get(partition.size() - 1).getMobile());
partition.add(newone);
}
}
分区类
public class Partitioning {
private ArrayList mobile;
private ArrayList cloud;
public Partitioning(ArrayList mobile, ArrayList cloud) {
this.mobile = mobile;
this.cloud = cloud;
}
public ArrayList getCloud() {
return cloud;
}
public void setCloud(ArrayList cloud) {
this.cloud = cloud;
}
public ArrayList getMobile() {
return mobile;
}
public void setMobile(ArrayList mobile) {
this.mobile = mobile;
}
@Override
public String toString() {
return "S1=" + mobile + " S2=" + cloud + "\n";
}
}
nums = 3时输出
[S1=[1] S2=[2, 3]
, S1=[2] S2=[1, 3]
, S1=[3] S2=[1, 2]
, S1=[2, 3] S2=[1]
, S1=[1, 3] S2=[2]
, S1=[1, 2] S2=[3]
, S1=[1, 2, 3] S2=[]
, S1=[] S2=[1, 2, 3]
]
8
当nums为2和3时有效,当nums&gt; 3时无效。我知道我的代码不完整,我没有得到通用逻辑如何解决这个问题,请帮帮我。