Subsets II
Description
Given a collection of integers that might contain duplicate numbers, return all possible subsets.
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
if(nums == null){
return null ;
}
Arrays.sort(nums) ;
List<List<Integer>> results = new ArrayList<>() ;
helper(nums , results , new ArrayList<Integer>() , 0) ;
return results ;
}
public void helper(int[] nums , List<List<Integer>> results , List<Integer> subset , int startIndex){
results.add(new ArrayList<Integer>(subset)) ;
for(int i = startIndex ; i < nums.length ; i++){
if(i != startIndex && nums[i] == nums[i-1]){
continue ;
}
subset.add(nums[i]) ;
helper(nums , results , subset , i+1);
subset.remove(subset.size()-1);
}
}
}
这篇博客介绍了如何使用Java实现一个解决方案,来生成一个整数数组中所有可能的子集,包括重复元素。核心算法采用了回溯法,并通过排序避免了重复子集的生成。该算法首先对输入数组进行排序,然后通过递归助手函数遍历所有可能的子集组合。
2656

被折叠的 条评论
为什么被折叠?



