题目:输入一个集合,输出他的子集
举例:输入集合[1,2],输出它的所有子集为[[], [1], [2], [1, 2]]
解题思路:1.采用位运算;2.对于集合中的每一位元素,只有两种状态[输出,不输出],用1代表输出,用0代表不输出;3.共有2^[集合个数]次;4.计算两次,一次&运算,一次>>运算
语言:java
代码如下:
public class Test{
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;
}
public static void main(String[] args){
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
System.out.println(getSubSet(list));
}
}