我正在尝试解决subset-II leetcode问题。
问题说明:给定一个整数集合,其中可能包含重复的nums,返回所有可能的子集(幂集)。解决方案集不得包含重复的子集。下面是我尝试过的代码。
private boolean isAlreadyExplored(int [] nums , int currElem , int currElemIndex) {
for(int i=0;i<currElemIndex;i++) {
if(currElem==nums[i]) {
System.out.println("Already exposed : " +currElem + " i : " + i);
return true;
}
}
return false;
}
private void subsetsWithDupHelper(int[] nums,List<List<Integer>> choosenList , List<Integer> choosen , int start) {
choosenList.add(new ArrayList<Integer>(choosen));
for(int i=start;i<nums.length; i++) {
//Explore only when the current elem's duplicate is not explored already.
if(i>start&&isAlreadyExplored(nums,nums[i],i)) { // i> start - this will skip the check for first elem.
continue;
}
choosen.add(nums[i]);
subsetsWithDupHelper(nums, choosenList, choosen, i+1); // increasing the start bcoz we are not repitating.
choosen.remove(choosen.size()-1); //backtrack.
}
}
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> choosenList = new ArrayList<>();
List<Integer> choosen = new ArrayList<Integer>();
//Arrays.sort(nums); // If i uncomment this line it is working.
subsetsWithDupHelper(nums, choosenList, choosen, 0);
return choosenList;
}
我写的代码没有Arrays.sort(nums);
,然后在讨论论坛中看到一些建议对输入进行排序。当我尝试对输入进行排序时,我的代码有效。
但是我不明白为什么需要排序?
有人可以帮助我了解我的缺失吗?在这里排序的意义是什么?