【LeetCode每日一题】78. 子集
78. 子集
题目来源link
算法思想:集合,位运算;
{1,2,3}集合
利用二进制排列:000,001,010,011,100,101,110,111
生成相应子集
java代码
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp;//用来存放生成的一个集合
int numSubset = (int) Math.pow(2, nums.length);//元素数量为n的集合拥有的子集数量为2^n
for (int i = 0; i < numSubset; i++) {
//生成2^n子集,序号为{000,001,010,,,}
temp = new ArrayList<Integer>();//每一次都要new新的集合来存放
for (int j = 0; j < nums.length; j++) {
//一个子集利用二级制来生成
if((1<<j & i) != 0) {
//用001(1)来位移,& 当前序号i,判断序号中第几位是1,然后将对应数组元素放入集合中
temp.add(nums[j]);
}
}
res.add(temp);
}
return res;
}
}