您的位置:首页 > 其它

[LeetCode]Permutations II

2016-10-18 16:48 288 查看
Question

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],

[2,1,1]

]

本题难度Medium。

【复杂度】

时间 O(N!) 空间 O(N)

【思路】

与Permutations不一样的地方就是有duplicates。办法就是跳过duplicates(29-33行)。其他不变。

【代码】

public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
//require
List<List<Integer>> ans=new ArrayList<>();
if(nums==null)
return ans;
int size=nums.length;
if(size<1)
return ans;
List<Integer> list=new ArrayList<Integer>(),remains=new ArrayList<Integer>();
for(int n:nums)
remains.add(n);
//invariant
helper(list,remains,ans);
//ensure
return ans;
}

private void helper(List<Integer> preList,List<Integer> remains,List<List<Integer>> ans){
//bound
if(remains.size()==0){
List<Integer> list=new ArrayList<Integer>(preList);
ans.add(list);
return;
}
Set<Integer> set=new HashSet<Integer>();
for(int i=0;i<remains.size();i++){
int n=remains.get(0);
if(set.contains(n)){
remains.remove(0);
remains.add(n);
continue;
}
set.add(n);
remains.remove(0);
preList.add(n);
helper(preList,remains,ans);
remains.add(n);
preList.remove(preList.size()-1);
}
}
}


参考

[LeetCode]Permutations
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode