78 Subsets
Given a set ofdistinctintegers,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],
[]
]
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null ){
return ans;
}
if (nums.length == 0) {
ans.add(new ArrayList<Integer>());
return ans;
}
Arrays.sort(nums);
List<Integer> sub = new ArrayList<Integer>();
helper(ans, sub, nums, 0);
return ans;
}
public void helper(List<List<Integer>> ans, List<Integer> sub, int[] nums, int startIdx) {
ans.add(new ArrayList<Integer>(sub));
if (startIdx == nums.length) {
return;
}
for (int i = startIdx; i < nums.length; i++) {
sub.add(nums[i]);
helper(ans, sub, nums, i+1);
sub.remove(sub.size() - 1);
}
}
}
**** Thing is you really do not understand what is subset!!
ans.add(new ArrayList<>(sub));
if (startIdx == nums.length) {
return;
}