【LeetCode题解】47. 全排列 II

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

输入: [1,1,2]
输出:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    List<List<Integer>> ret = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);//先排序
        int[] tmp = new int[nums.length];
        boolean[] vis = new boolean[nums.length];
        for(int i=0 ; i<nums.length ; i++){
            tmp[0] = nums[i];
            vis[i] = true;
            permute(nums, i ,tmp, 0, vis);
            vis[i] = false;
        }
        return ret;
    }
    
    void permute(int[] nums, int n, int[] cur, int k, boolean[] v){
        /** 
        这里去重不可以单纯判断是否排序后的nums[i] == nums[i-1]
        因为这是排列,不管是不是重复,[1,1]得排成[1,1]而不是第一个[1]出现后忽略第二个[1]
        评论中给了一个很好的思路,用另一个visited[]记录上个元素是否被访问过
        因为是按照排序的顺序选择,所以上个元素i-1一旦被选择过,必然是在上一轮选择,则此时选择i没问题
        若上一个元素i-1未被选择过,则必然是for循环分别访问,则此时访问i会出现重复
        */
        if(n!=0 && nums[n]==nums[n-1] && !v[n-1]){//与上一个数字相等且上一个数字未被访问过
            return ;
        }
        if(k == cur.length-1){
            List<Integer> tmp = new ArrayList<>();
            for(int val:cur){
                tmp.add(val);
            }
            ret.add(new ArrayList<Integer>(tmp));
            return ;
        }
        for(int i=0 ; i<nums.length ; i++){
            if(v[i]){
                continue;
            }
            cur[k+1] = nums[i];
            v[i] = true; 
            permute(nums, i ,cur , k+1, v);
            v[i] = false; 
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章