题目
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], [] ]
The power set (or powerset) of any set S is the set of all subsets of S, including the empty set and Sitself,
十分钟尝试
这个题目可以用回溯法,跟圆括号和排序组合题目一样,但是每个解的出口条件是什么?
看了一个回溯解法,跟排列组合不同的是,第一:没有出口条件,tmpList元素递归调用是无条件加入list。
第二,有个start index。
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list=new ArrayList();
backTrace(list, new ArrayList(),nums,0);
return list;
}
//出口条件怎写?不同于排序组合,怎么产生1,2,3,以及1,2等不是3个元素的子集
private void backTrace(List<List<Integer>> list, List<Integer> tmpList,int[] nums,int start){
//不同于组合排列,组合排列是从0开始,判断是否存在。这个变化start index,并且start index是终止条件
list.add(new ArrayList(tmpList));
for(int i=start;i<nums.length;i++){
tmpList.add(nums[i]);
backTrace(list, tmpList,nums,i+1);
tmpList.remove(tmpList.size()-1);
}
}
}