Given a set of distinct integers, nums, return all possible subsets.
Note:
For example,
If nums = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Subscribe to see which companies asked this question
Discuss
这道题要求一个集合的所有子集。如果一个集合有n个元素,那么会有2的n次方个子集。用深搜求解。
我的AC代码
public class Subsets {
public static void main(String[] args) {
int[] a = { 1, 2, 3 };
System.out.println(subsets(a));
}
public static List> subsets(int[] nums) {
List> ll = new ArrayList>();
Arrays.sort(nums);
dfs(nums, new ArrayList(), 0, ll);
return ll;
}
private static void dfs(int[] nums, ArrayList l, int i, List> ll) {
if (i == nums.length) {
ll.add((List) l.clone());
return;
}
l.add(nums[i]);
dfs(nums, l, i + 1, ll);
l.remove(l.size() - 1);
dfs(nums, l, i + 1, ll);
}
}