牛客地址
解题思路
假设集合的大小为n,则子集的个数为
从遍历,对每一个数字进行二进制的判断。
实现代码
import java.util.*;
public class Solution {
private ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
if(S == null || S.length == 0){
return res;
}
int len = S.length;
for(int mask = 0; mask < (1 << len); mask++){
ArrayList<Integer> path = new ArrayList<>();
for(int i = 0; i < len; i++){
if(mask > 0 && ((mask & (1 << i)) > 0)){
path.add(S[i]);
}
}
res.add(new ArrayList<Integer>(path));
}
return res;
}
}