Description
Given a set of distinct integers, nums, return all possible subsets.
Note: 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],
[]
]
Solution
DFS
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> subsets = new LinkedList<>();
if (nums == null || nums.length < 1) {
return subsets;
}
subsetsRecur(0, nums, new LinkedList<>(), subsets);
return subsets;
}
public void subsetsRecur(int i, int[] nums, List<Integer> subset
, List<List<Integer>> subsets) {
if (i == nums.length) {
subsets.add(new LinkedList<>(subset));
return;
}
subsetsRecur(i + 1, nums, subset, subsets);
subset.add(nums[i]);
subsetsRecur(i + 1, nums, subset, subsets);
subset.remove(subset.size() - 1);
}
}