1、題目
冪集。編寫一種方法,返回某集合的所有子集。集合中不包含重複的元素。
說明:解集不能包含重複的子集。
示例:
輸入: nums = [1,2,3]
輸出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/power-set-lcci
2、解題思路
[1, 2, 3] 有三位, 用二進制表示就是 000, 001, 010, 011, 100, 101, 110, 111 代表了全部子集。所以我們可以利用位運算來進行求解。
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> returnList = new ArrayList();
int total = 1 << nums.length;
for(int i = 0;i <total; i++){
List<Integer> list = new ArrayList();
int temp = i;
if(temp != 0){
int index = 0;
while(temp != 0){
if((temp & 1) == 1){
list.add(nums[index]);
}
temp = temp >> 1;
index++;
}
}
returnList.add(list);
}
return returnList;
}
}