Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
Subscribe to see which companies asked this question
这道题目和上题思路差不多,不过要考虑去重。
如果对于每一个候选的解都查看当前结果集中是否包含该解,效率就太低了。
一个比较好的方法就是一开始对于给定的集合先排好序,然后递归过程中,每次扩展新节点,检查该节点和上次扩展的节点是否相同,相同则不扩展。
下面是JAVA实现:
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> middle = new ArrayList<Integer>();
Arrays.sort(nums);
for(int i = 0 ; i < nums.length ; i ++){
middle.add(nums[i]);
}
List<Integer> path = new ArrayList<Integer>();
getPermute(res, middle, path);
return res;
}
public void getPermute(List<List<Integer>> res,List<Integer> nums,List<Integer> path){
if(nums.size() == 0){
res.add(new ArrayList<Integer>(path));
}
else{
for(int i = 0 ; i < nums.size() ; i++){
if(i > 0 && nums.get(i-1).intValue() == nums.get(i).intValue())
continue;
path.add(nums.get(i));
nums.remove(i);
getPermute(res, nums, path);
nums.add(i,path.remove(path.size() -1));
}
}
}
}
本文探讨如何在存在重复元素的数集上生成所有唯一排列。通过预先排序集合并递归过程中的智能决策,避免重复扩展路径,提高效率。Java实现展示了这一策略的应用。
2549

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



