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], [] ]题意:求集合的所有子集合。
思路:dfs。方法与题
combinations方法一样。
代码:
public class Solution {
public static void dfs(List<ArrayList<Integer>> result, List<Integer> tmp, int depth ,int count, int[] S, int k)
{
if(count == k)
{
result.add(new ArrayList<Integer>(tmp));
return;
}
if(count > k)
return;
for(int i = depth; i < S.length; i++)
{
tmp.add(S[i]);
count++;
dfs(result, tmp, i + 1,count, S, k);
count--;
tmp.remove(tmp.size() - 1);
}
}
public static List<ArrayList<Integer>> subsets(int[] S)
{
int length = S.length;
Arrays.sort(S);
List<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
List<Integer> tmp = new ArrayList<Integer>();
for(int i = 0; i <= length; i++)
dfs(result, tmp, 0, 0, S, i);
return result;
}
}