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], [] ]
思路: 深度优先, 回溯剪枝 dfs backtracking
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0){
return result;
}
List<Integer> list = new ArrayList<Integer>();
dfs(result, list, nums, 0);
return result;
}
public void dfs(List<List<Integer>> result, List<Integer> list,int[] nums, int position){
if(position > nums.length){
return;
}
result.add(new ArrayList<Integer>(list));
for(int i = position; i < nums.length; i++){
list.add(nums[i]);
dfs(result, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}