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],
[]
]
一刷
题解:
back tracking
需要补充的点:怎么求时间复杂度,还有怎么用bit manipulation
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums == null || nums.length == 0) return res;
boolean[] visited = new boolean[nums.length];
subsets(res, nums, new ArrayList<Integer>(), visited, 0);
return res;
}
private void subsets(List<List<Integer>> res, int[] nums, List<Integer> list, boolean[] visited, int pos){
res.add(new ArrayList<Integer>(list));
for(int i=pos; i<nums.length; i++){
if(!visited[i]){
list.add(nums[i]);
visited[i] = true;
subsets(res, nums, list, visited, i+1);
list.remove(list.size()-1);
visited[i] = false;
}
}
}
}
二刷:
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
dfs(res, list, nums, 0);
return res;
}
private void dfs(List<List<Integer>> res, List<Integer> list, int[] nums, int pos){
res.add(new ArrayList<>(list));
for(int i=pos; i<nums.length; i++){
list.add(nums[i]);
dfs(res, list, nums, i+1);
list.remove(list.size()-1);
}
}
}