78.子集
难度:中等
标签:回溯算法
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
思路:
这里是求子集,每添加一个数进去就是一个子集,和原来集合相同的子集需要单独添加进去.
public class Solution {
boolean flag;
public static void main(String[] args) {
int[] a={1,2,3};
new Solution().subsets(a);
}
public List<List<Integer>> subsets(int[] nums){
List<List<Integer>> lists=new ArrayList<>();
if(nums==null||nums.length==0)
return lists;
Deque<Integer> path= new ArrayDeque<>();
boolean used[]=new boolean[nums.length];
flag=true;
dfs(0,lists,path,nums,used);
return lists;
}
private void dfs(int pos,List<List<Integer>> lists, Deque<Integer> path,int[] nums,boolean[] used) {
lists.add(new ArrayList<>(path));
for(int i=pos;i<nums.length;i++){
if(used[i]) continue;
path.addLast(nums[i]);
used[i]=true;
//单独考虑全集,flag用来只添加一次
if(flag&&path.size()==nums.length){
lists.add(new ArrayList<>(path));
flag=false;
path.removeLast();
used[i]=false;
break;
}
dfs(i+1,lists,path,nums,used);
path.removeLast();
used[i]=false;
}
}
}