题目
给定一个含不同整数的集合,求出其所有的子集.
输入 [1,2,3] 输出: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
分析
- 空集合 输入:[] 输出: [[]]
- 1个元素 输入:[1] 输出:[[],[1]]
- 2个元素 输入:[1,2] 输出:[[], [1], [2], [1, 2]]
仔细看上面的输出,可以看出,对于某一位元素,只有2种状态,输出与不输出.
[1,2] 11 [1,2]
[1,2] 10 [1]
[1,2] 01 [2]
[1,2] 00 []
其子集的个数为2^{集合大小}
实现
根据上面的规律,根据位运算求解一个集合的子集方法可以如下实现:
package me.qianlv;
import java.util.ArrayList;
import java.util.List;
/**
* @author xiaoshu
*/
public class SubArray {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(getSubSet(list));
}
public static List<List<Integer>> getSubSet(List<Integer> list) {
if (null == list || list.isEmpty()) {
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0, size = (int) Math.pow(2, list.size()); i < size; i++) {
List<Integer> subSet = new ArrayList<>();
int index = i;
for (int j = 0; j < list.size(); j++) {
if ((index & 1) == 1) {
subSet.add(list.get(j));
}
index >>= 1;
}
result.add(subSet);
}
return result;
}
}
输出结果为:
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
算法真是太有魅力了!!!在下折服~