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], [] ]
算法思路:例如{1,2}的全部子集为{}{1}{2}{1,2}不妨假设为s1,加入3之后即{1,2,3}的全部子集该如何得到呢?简单一点方法就是将3依次加入{1,2}的子集当中得到新的子集{3}{1,3}{2,3}{1,2,3}设为s2,
s1∩s2即为{1,2,3}的全部子集。
public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> re = new ArrayList<List<Integer>>(); re.add(new ArrayList<Integer>());//初始化,加入空集 Arrays.sort(nums); for(int i:nums) { List<List<Integer>> tmp = new ArrayList<List<Integer>>(); for(List<Integer> set:re) { List<Integer> tmp_set = new ArrayList<Integer>(); tmp_set.addAll(set);//clone原来存在的list tmp_set.add(i); tmp.add(tmp_set); } re.addAll(tmp); } return re; } }