[LeetCode]Permutations II

来源:互联网 发布:数据充值 编辑:程序博客网 时间:2024/05/15 01:36

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

0 0