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],
[]
]
使用回溯法,具体可参考Combination Sum中的讲解。
针对这题我们需要求出给定集合的所有子集,所以当然也包括空集。以[1,2,3]为例,搜索的策略:
- 先把空集加入到返回链表;
- 再有下图的顺序搜索得到所有的解。
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new LinkedList<List<Integer>>();
subsetsBacktrack(res,new LinkedList<Integer>(),nums,0);
return res;
}
private void subsetsBacktrack(List<List<Integer>> subsetsList,LinkedList<Integer> tempList,int[] nums,int start)
{
subsetsList.add(new LinkedList<Integer>(tempList));
for(int i=start;i<nums.length;++i)
{
tempList.add(nums[i]);
subsetsBacktrack(subsetsList,tempList,nums,i+1);
tempList.remove(tempList.size()-1);
}
}
}