【LeetCode】90.Subsets II(Medium)解题报告
题目地址:https://leetcode.com/problems/subsets-ii/description/
题目描述:
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example, If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
给的集合里面可能有重复数字。模板backtracking。
Solutions:
/*
time:O(2^n)
space:O(n)
*/
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums==null || nums.length==0) return res;
Arrays.sort(nums);
helper(res,new ArrayList<>(),nums,0);
return res;
}
public void helper(List<List<Integer>> res , List<Integer> temp , int[] nums,int index){
//if(nums==null || nums.length==0) return;
res.add(new ArrayList<>(temp));
for(int i = index ; i<nums.length ; i++){
if(i!=index && nums[i]==nums[i-1]) continue; //去重经典操作
temp.add(nums[i]);
helper(res,temp,nums,i+1);
temp.remove(temp.size()-1);
}
}
}
Date:2018年1月3日