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], [] ]
题意:给出一个集合,集合中的元素不相等,求其所有的集合
思路:用DFS,先求出一个元素的集合,然后在生成的集合上再生成新的集合,如[1,2],先生成[],[2],然后再考虑1情况下,生成的新集合有[1],[1,2]
注意,在处理前,数据要先排序
代码如下
public class Solution { private List<List<Integer>> dfs(int cur, int n, int[] nums) { if (cur == n) { List<List<Integer>> ans = new LinkedList<List<Integer>>(); List<Integer> ar = new LinkedList<Integer>(); ans.add(ar); ar = new LinkedList<Integer>(); ar.add(nums[n]); ans.add(ar); return ans; } List<List<Integer>> ans = new ArrayList<List<Integer>>(); List<List<Integer>> tmp = dfs(cur + 1, n, nums); for (int j = 0; j < tmp.size(); j++) { ans.add(tmp.get(j)); } for (int j = 0; j < tmp.size(); j++) { List<Integer> node = new LinkedList<Integer>(); node.addAll(tmp.get(j)); node.add(0, nums[cur]); ans.add(node); } return ans; } public List<List<Integer>> subsets(int[] nums) { int n = nums.length; Arrays.sort(nums); return dfs(0, n - 1, nums); } }