給定一組不含重複元素的整數數組 nums,返回該數組全部可能的子集(冪集)。數組
說明:解集不能包含重複的子集。網絡
示例:code
輸入: nums = [1,2,3]
輸出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]]leetcode
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/subsets
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。get
2^4==1<<len
。((bitMask >> i) & 1)
能夠判斷掩碼的哪些位爲1。故每條掩碼對應一個子集。回溯法待作。it
public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> subSetList = new LinkedList<>(); int len = nums.length; int subSetCnt = 1 << len;// 子集數目 for (int bitMask = 0; bitMask < subSetCnt; ++bitMask) { List<Integer> subSet = new LinkedList<>(); for (int i = 0; i < len; ++i) { if (((bitMask >> i) & 1) == 1) { // 若是掩碼第(低)i位爲1 subSet.add(nums[i]); } } subSetList.add(subSet); } return subSetList; }
public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> subSetList = new LinkedList<>(); int len = nums.length; subSetList.add(new LinkedList<>()); for (int i = 0; i < len; ++i) { int curSubSetCnt = subSetList.size(); for (int j = 0; j < curSubSetCnt; ++j) { // 注意這裏用常數curSubSetCnt,保證只遍歷列表未加入這個元素以前的全部子集 List<Integer> newSebSet = new LinkedList<>(subSetList.get(j)); newSebSet.add(nums[i]); subSetList.add(newSebSet); } } return subSetList; }