« Back
read.

Leetcode 78 Subsets.

Leetcode 78 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],
  []
]

The solution comes from discuss part of that problem, very clear way to finish this problem.

public class Solution {
    public List> subsets(int[] nums) {


    Arrays.sort(nums);
    int totalnumber=1 << nums.length;
    List < List< Integer> > collection =new ArrayList< List< Integer>>(totalnumber);
    for(int i=0;i < totalnumber;i++){
        List set=new ArrayList();
        for(int j=0;j < nums.length;j++){
            if((i & (1 << j)) !=0){
                set.add(nums[j]);
            }

        }
        collection.add(set);

    }
    return collection;
    }
}
comments powered by Disqus