问题如下:
Given a set of distinct integers, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
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],
[]
]
分析:还是使用递归的方法。
代码如下:272ms
public class Solution {
private void solve(List<List<Integer>> res,int[] nums,List<Integer> tmpList,int index){
if(index==nums.length){
res.add(new LinkedList(tmpList));
return;
}
solve(res,nums,tmpList,index+1);
tmpList.add(nums[index]);
solve(res,nums,tmpList,index+1);
tmpList.remove(tmpList.size()-1);
}
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
List<Integer> tmpList = new LinkedList<>();
Arrays.sort(nums);
solve(res, nums, tmpList, 0);
return res;
}
}