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的位置对应的数组元素加入到子集中。

 1 class Solution {
 2     public List<List<Integer>> subsets(int[] nums) {
 3         //int len = nums.length;
 4         int end = (int)Math.pow(2,nums.length);
 5         List<List<Integer>> res = new ArrayList<>();
 6         for(int i = 0; i < end; i++)
 7         {
 8             res.add(subset(nums,i));
 9         }
10         return res;
11     }
12     
13     public List<Integer> subset(int[] nums, int m)
14     {
15         List<Integer> res = new ArrayList<>();
16         int i = 0;
17         while(m != 0)
18         {
19             if(m % 2 != 0)
20             {
21                 res.add(nums[i]);
22             }
23             m = m / 2;
24             i++;
25         }
26         return res;
27     }
28 }
原文地址:https://www.cnblogs.com/yanhowever/p/10713548.html