Power Set: Write a method to return all subsets of a set.
subset 1;没有重复数字;
public class Solution {
/**
* @param nums: A set of numbers
* @return: A list of lists
*/
public List<List<Integer>> subsets(int[] nums) {
// write your code here
List<List<Integer>> resultList = new ArrayList<>();
//if(nums == null || nums.length == 0) return resultList;
Arrays.sort(nums);
List<Integer> result = new ArrayList<Integer>();
helper(nums, result, resultList, 0);
return resultList;
}
public void helper(int[] nums, List<Integer> result, List<List<Integer>> resultList, int start) {
resultList.add(new ArrayList<Integer>(result));
for(int i = start; i <nums.length; i++) {
result.add(nums[i]);
helper(nums, result, resultList, i + 1);
result.remove(result.size() - 1);
}
}
}
subset 2;有重复数字;
public class Solution {
/**
* @param nums: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public List<List<Integer>> subsetsWithDup(int[] nums) {
// write your code here
List<List<Integer>> resultList = new ArrayList<>();
Arrays.sort(nums);
helper(nums, resultList, new ArrayList<Integer>(), 0);
return resultList;
}
public void helper(int[] nums, List<List<Integer>> resultList, List<Integer> result, int start) {
resultList.add(new ArrayList<Integer>(result));
for(int i = start; i < nums.length; i++) {
if(i > start && nums[i] == nums[i - 1]) {
continue;
}
result.add(nums[i]);
helper(nums, resultList, result, i + 1);
result.remove(result.size() - 1);
}
}
}