题目
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<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list_of_lists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
subsets(nums, list_of_lists, list, 0);
return list_of_lists;
}
public void subsets(int[] nums, List<List<Integer>> list_of_lists, List<Integer> curr_list, int curr_index) {
if(curr_index == nums.length) {
list_of_lists.add(new ArrayList<Integer>(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<List<Integer>> subsets(int[] nums) {
//Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
ans.add(new ArrayList<Integer>());
for(int i = 0; i < nums.length; i++) {
for(int j = 0, size = ans.size(); j < size; j++) {
List<Integer> subset = new ArrayList<>(ans.get(j));
subset.add(nums[i]);
ans.add(subset);
}
}
return ans;
}
}
利用bits来指导是否选取某一个数字入subset
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
int num_subsets = 1 << nums.length;
for(int i = 0; i < num_subsets; i++) {
List<Integer> list = new ArrayList<Integer>();
for(int j = 0; j < nums.length; j++) {
if(((i >> j) & 1) == 1)
list.add(nums[j]);
}
ans.add(list);
}
return ans;
}
}