LeetCode Q 78 - Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Solution : Backtracking
Code:
private List<List<Integer>> res;
public List<List<Integer>> subsets(int[] nums) {
res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
backtrack(nums, 0, new ArrayList<>());
return res;
}
private void backtrack(int[] nums, int pos, List<Integer> temp) {
res.add(new ArrayList(temp));
for (int i = pos; i < nums.length; i++) {
temp.add(nums[i]);
backtrack(nums, i + 1, temp);
temp.remove(temp.size() - 1);
}
}