* 主题思想:* 这题解法是回溯法,典型的搜索题。 和permutation 以及subset是同样类型的题。 这题主要复杂在有相同数字,需要跳过
这里记录下一种通用的解法:
- 首先排序,
- 回溯法,搜索
- 搜索中根据题目要求,跳过相同数字
AC 代码:
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
// important need sort first
Arrays.sort(nums);
backtrack(ans,new ArrayList<Integer>(),nums,0);
return ans;
}
public void backtrack(List<List<Integer>> ans,List<Integer> tmp, int[] nums, int start){
ans.add(new ArrayList<Integer>(tmp));
for(int i=start;i<nums.length;i++){
// here skip duplicates
if(i>start&&nums[i]==nums[i-1]) continue;
tmp.add(nums[i]);
backtrack(ans,tmp,nums,i+1);
tmp.remove(tmp.size()-1);
}
return ;
}
}