[LeetCode Daily Question] 78. Subset
78. Subset
Topic source link
algorithm idea: set, bit operation;
{1,2,3} Set
Use binary arrangement: 000,001,010,011,100,101,110,111 to
generate corresponding subset
java code
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;
}
}