Subsets

题目
Given a set of distinct integers, nums, return all possible subsets (the power set).

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

答案

class Solution {
    public List> subsets(int[] nums) {
        List> list_of_lists = new ArrayList>();
        List list = new ArrayList();
        subsets(nums, list_of_lists, list, 0);
        return list_of_lists;
    }

    public void subsets(int[] nums, List> list_of_lists, List curr_list, int curr_index) {
        if(curr_index == nums.length) {
            list_of_lists.add(new ArrayList(curr_list));
            return;
        }
        curr_list.add(nums[curr_index]);
        subsets(nums, list_of_lists, curr_list, curr_index + 1);
        curr_list.remove(curr_list.size() - 1);
        subsets(nums, list_of_lists, curr_list, curr_index + 1);
    }}

上面这个代码效率似乎有点低,大概是因为递归和大量的列表add 和remove的操作
下面这个代码效率高很多

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

利用bits来指导是否选取某一个数字入subset

class Solution {
    public List> subsets(int[] nums) {
        List> ans = new ArrayList>();
        int num_subsets = 1 << nums.length;
        for(int i = 0; i < num_subsets; i++) {
            List list = new ArrayList();
            for(int j = 0; j < nums.length; j++) {
                if(((i >> j) & 1) == 1) 
                    list.add(nums[j]);
            }
            ans.add(list);
        }
        return ans;
    }
}

你可能感兴趣的:(Subsets)