Leetcode:Subsets

来源:互联网 发布:云计算到底哪家强 编辑:程序博客网 时间:2024/05/18 18:47

Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note:

Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

两种方式,第一种直观的方式,就是先把空集加入List中,然后每个新进入list的元素,都要和前面已经存在的list元素做一次合并,如下

1 将空集放入 [ [] ]
2 将nums[0]放入(与[]合并) [[],nums[0] ]
3 将nums[1]放入(与[]合并,与nums[0]合并)
[[],[nums[0]],[nums[1]],[nums[0],nums[1]]]
每次都和前面的元素一一匹配一下,最后就会得到所有子集
代码如下:

public class Solution {    public List<List<Integer>> subsets(int[] nums) {        List<List<Integer>> subs=new ArrayList<>();        List<Integer> tmp = new ArrayList<Integer>();        subs.add(tmp);        Arrays.sort(nums);        for(int i=0;i<nums.length;i++){            int count=subs.size();            for(int j=0;j<count;j++){                tmp=new ArrayList<>(subs.get(j));                tmp.add(nums[i]);                subs.add(tmp);            }        }        return subs;    }}

还有一种更精妙的解法:
假设nums={1,2,3},总共有8个子集,用bit位可以表示
这里可以把最高位看做是3,最低位是1,每位上1表示有,0表示没有
那么
0 0 0 = [ ]
0 0 1 = [1]
0 1 0 = [2]
0 1 1 = [1,2]
1 0 0 = [3]
1 0 1 = [1,3]
1 1 0 = [2,3]
1 1 1 = [1,2,3]
这样就求出来了
我们可以在最外层设一个循环 i= 0 - 2^(nums.length)
在这个例子中 就产生了0-7,8个数字,只需要判断这8个数字的bit位中为1的位是哪些即可

代码如下:

public class Solution {    public List<List<Integer>> subsets(int[] nums) {        int count=(int)Math.pow(2,nums.length);        List<List<Integer>> subs=new ArrayList<>();        Arrays.sort(nums);        for(int i=0;i<count;i++){            List<Integer> sub = new ArrayList<>();            for(int j=0;j<nums.length;j++){                if(((i>>j)&1)==1){                    sub.add(nums[j]);                }            }            subs.add(sub);        }        return subs;    }}
0 0