【leetcode刷题笔记】Subsets
Given a set of distinct integers, S, 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 S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
题解:实现一个递归的函数生成长度为level的所有子集放入结果中,然后循环的置这个level为0~S.length,即可生成所有的子集。
代码如下:
1 public class Solution { 2 public void subsetsDfs(int[] s,int level,int pos,ArrayList<Integer> result,List<List<Integer>> answer){ 3 if(result.size() == level){ 4 answer.add(new ArrayList<Integer>(result)); 5 return; 6 } 7 for(int i = pos;i < s.length;i++){ 8 result.add(s[i]); 9 subsetsDfs(s, level, i+1, result, answer); 10 result.remove(result.size()-1); 11 } 12 } 13 public List<List<Integer>> subsets(int[] S) { 14 Arrays.sort(S); 15 List<List<Integer>> answer = new ArrayList<List<Integer>>(); 16 ArrayList<Integer> result = new ArrayList<Integer>(); 17 18 for(int i = 0;i <= S.length;i++) 19 subsetsDfs(S, i, 0, result, answer); 20 return answer; 21 } 22 }