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],
[]
]
主题思想: 这个和77 题同样是通过回溯完成的,形成了一个比较典型的方法吧
AC 代码:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
Arrays.sort(nums);
dfs(nums,ans,new ArrayList<Integer>(),0);
return ans;
}
public void dfs(int[] nums,List<List<Integer>>ans,List<Integer> tmp,int start){
ans.add(new ArrayList<Integer>(tmp));
for(int i=start;i<nums.length;i++){
tmp.add(nums[i]);
dfs(nums,ans,tmp,i+1);
tmp.remove(tmp.size()-1);
}
}
}
本文介绍了一种生成给定整数数组所有可能子集(幂集)的算法,并提供了详细的AC代码实现。该算法采用回溯法,确保解决方案集中不包含重复的子集。
629

被折叠的 条评论
为什么被折叠?



