0
点赞
收藏
分享

微信扫一扫

【leetcode】47. 全排列 II(dfs+回溯、剪枝)

题目:

47. 全排列 II
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:

输入:nums = [1,1,2]
输出:
[[1,1,2],
 [1,2,1],
 [2,1,1]]
示例 2:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

提示:
1 <= nums.length <= 8
-10 <= nums[i] <= 10

回溯+dfs :
与46.全排列多的点是给nums数组排序和之后剪枝(去重)。

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;
        if(len == 0) return res;
        boolean[] used = new boolean[len];
        Arrays.sort(nums);  //为了下面方便通过相邻节点判断是否重复使用了
        List<Integer> path = new ArrayList<>();
        dfs(nums,len,path,0,used,res);
        return res;
    }
    public void dfs(int[] nums,int len,List<Integer> path,int depth,boolean[]used,List<List<Integer>> res){
        if(depth == len){
            // 深拷贝(开辟新的空间)
            res.add(new ArrayList(path));
            return;
        }
        for(int i = 0;i < len;i++){
            // 这一次使用的数如果和上一次使用的数相等,而且上一次使用的数刚刚撤销,则剪枝
            if(i > 0 && !used[i - 1] && nums[i-1] == nums[i]) {   
                continue;
            }
            if(!used[i]){
                path.add(nums[i]);
                used[i] = true;
                dfs(nums,len,path,depth+1,used,res);
                used[i] = false;
                path.remove(path.size()-1);
            } 
        }
    }
}

在这里插入图片描述

举报

相关推荐

0 条评论