leetcode 78. 子集 JAVA

题目:

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

思路:

位运算,求出数组nums的长度n,则一共有2^n个子集,则从0遍历到2^ n - 1,将其转换成2进制数,将2进制数中为1的位置对应的数组元素加入到子集中。

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        int end = (int)Math.pow(2,nums.length);
        for(int i = 0;i<end;i++)
            ans.add(helper(nums,i));
        return ans;
    }
    //把n化为二进制,0表示不取,1表示取
    public List<Integer> helper(int[] nums,int n){
        List<Integer> ans = new ArrayList<>();
        int i = 0;
        while(n!=0){
            if((n&1)==1)  //位运算
                ans.add(nums[i]);
            i++;
            n >>= 1; //n左移1位
        }
        return ans;
    }
}

猜你喜欢

转载自www.cnblogs.com/yanhowever/p/10713548.html