leetcode 78. Subsets

来源:互联网 发布:sql2000还原数据库 编辑:程序博客网 时间:2024/05/22 05:00

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

Note: 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],  []]
蛮简单的题目,用递归就能完成:当前元素:取/不取,再递归到下一个元素。

public List<List<Integer>> subsets(int[] nums) {List<List<Integer>> result=new ArrayList<List<Integer>>();List<Integer> list=new ArrayList<>();helper(nums, 0,result,list);return result;}public void helper(int[] nums,int index,List<List<Integer>> result,List<Integer> list){if(index==nums.length){result.add(list);return;}List<Integer> newList=new ArrayList<>(list);helper(nums, index+1, result, newList);newList=new ArrayList<>(list);newList.add(nums[index]);helper(nums, index+1, result, newList);}
还有大神没有用递归,思路也很好。
起始subset集为:[]添加S0后为:[], [S0]添加S1后为:[], [S0], [S1], [S0, S1]添加S2后为:[], [S0], [S1], [S0, S1], [S2], [S0, S2], [S1, S2], [S0, S1, S2]红色subset为每次新增的。显然规律为添加Si后,新增的subset为克隆现有的所有subset,并在它们后面都加上Si
这样的话就只要迭代就能解决了。
public class Solution {    public List<List<Integer>> subsets(int[] S) {        List<List<Integer>> res = new ArrayList<>();        res.add(new ArrayList<Integer>());              Arrays.sort(S);        for(int i : S) {            List<List<Integer>> tmp = new ArrayList<>();            for(List<Integer> sub : res) {                List<Integer> a = new ArrayList<>(sub);                a.add(i);                tmp.add(a);            }            res.addAll(tmp);        }        return res;    }}
除这两种方法之外,大神还有另外一种与众不同的方法:bit-manipulation!
 {1 , 2 , 3 }的子集个数 = 2^3 . 为什么?  考虑到数组中每个元素是否取的情况  1   ->          取 or 不取 = 2   2   ->          取 or 不取 = 2    3   ->          取 or 不取 = 2  所以,总的情况 = 2*2*2 = 2^3 = { { } , {1} , {2} , {3} , {1,2} , {1,3} , {2,3} , {1,2,3} }让我们用 1 和 0 来表示取或者不取。数组中有三个元素,因此需要3个bit,其中低位->高位表示nums[0]~nums[n]取 = 1不取 = 0 0) 0 0 0  -> 不取 3 , 不取 2 , 不取 1 = { } 1) 0 0 1  -> 不取 3 , 不取 2 ,  取 1  =  {1 } 2) 0 1 0  -> 不取 3 ,  取 2  , 不取 1 = { 2 } 3) 0 1 1  -> 不取 3 ,  取 2  ,  取 1  = { 1 , 2 } 4) 1 0 0  ->  取 3  , 不取 2 , 不取 1 = { 3 } 5) 1 0 1  ->  取 3  , 不取 2 ,  取 1  = { 1 , 3 } 6) 1 1 0  ->  取 3  ,  取 2  , 不取 1 = { 2 , 3 } 7) 1 1 1  ->  取 3  ,  取 2  ,  取 1= { 1 , 2 , 3 } 在上面的逻辑中,只有当 (j>>i)&1 ==true   {其中 j ∈ {0,1,2,3,4,5,6,7},i 是 nums[]的索引} 时,才进行 Insert S[i] 的操作。 因此,数字1只有当最右bit是1的时候才被插入,( j = 1,3,5,7 时)数字2只有当第二右bit是1的时候才被插入,( j = 2,3,6,7 时)数字3只有当第三右bit是1的时候才被插入,( j = 4,5,6,7 时)该解法时间复杂度 : O(n * 2^n) 
public List<List<Integer>> subsets(int[] S) {Arrays.sort(S);int totalNumber = 1 << S.length;List<List<Integer>> collection = new ArrayList<List<Integer>>(totalNumber);for (int i=0; i<totalNumber; i++) {List<Integer> set = new LinkedList<Integer>();for (int j=0; j<S.length; j++) {if ((i & (1<<j)) != 0) {set.add(S[j]);}}collection.add(set);}return collection;}