递归解法
分析:
- 采用递归的方法将问题有简单到复杂
- 注意因为是集合里面套集合,况且各个每个集合元素不重复,可以用Set 里面套Set
- 当加入元素成为集合中时,不能直接改变他,要克隆到t2中,再添加。否则就会出现,元素重复的现象,因为前面先添加进去的集合会跟着改变
import java.util.HashSet;
import java.util.Set;
public class Main {
public static int a[] = {1,2,3};
public static void main(String[] args) {
System.out.println(ToDo(a.length));
}
private static Set<Set<Integer>> ToDo(int i) {
Set<Set<Integer>> twoSet = new HashSet<>();
//1 跳出条件
if(i == 1) {
Set<Integer> e = new HashSet<>();
e.add(a[0]);
twoSet.add(e);
return twoSet;
}
//2 先生成上一阶段
Set<Set<Integer>> tempSet = ToDo(i - 1);
//3 再生成本阶段
for(Set<Integer> t1 : tempSet) {
//不加入该元素
twoSet.add(t1);
//加入该元素
//t1.add(a[i - 1]);
HashSet<Integer> t2 = new HashSet<>();
t2 = (HashSet<Integer>) ((HashSet) t1).clone();
t2.add(a[i - 1]);
twoSet.add(t2);
}
//单独加入该元素
HashSet<Integer> e = new HashSet<>();
e.add(a[i - 1]);
twoSet.add(e);
return twoSet;
}
}
运行结果:
[[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
非空子集之二进制解法
分析:
- 直接用二进制的0代表放入,1代表不放入
public class Main {
public static int a[] = {1,2,3};
public static void main(String[] args) {
int n = a.length;
int ns = (int )Math.pow(2, n) - 1;
for(int i = 1; i <= ns; i ++) {
int t = i;
int j = 0;
while(t > 0) {
if((1 & t ) != 0) {
System.out.print(a[j] + " ");
}
t = t >> 1;
j ++;
}
System.out.println();
}
}
}
运行结果:
1
2
1 2
3
1 3
2 3
1 2 3