题目地址:Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
本题是在Combinations基础上进行的,主要思想还是回溯。
class Solution {
public List<List<Integer>> subsets(int[] nums) {
int len = nums.length+1;
List<List<Integer>> res = new ArrayList<>();
for(int i =0;i<len;i++){
combine(res,nums,i);
}
return res;
}
public void combine(List<List<Integer>> res,int[] nums,
int len) {
List<Integer> paramList = new ArrayList<Integer>();
DFS(res,paramList,nums,len,0);
}
public void DFS(List<List<Integer>> res,List<Integer> paramList,
int[] nums, int len,int index){
if(paramList.size() == len){
res.add(new ArrayList(paramList));
return ;
}
int length = nums.length;
for(int i=index; i< length; i++){
paramList.add(nums[i]);
DFS(res,paramList,nums,len,i+1);
paramList.remove(paramList.size()-1);
}
}
}