DFS_47. 全排列 II

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

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii


思路:

上一题是没有重复的数字,这题数字允许重复

总的思路和上一题一样,增加一个条件判断,判断当前形成的路径和上一条路径是不是相同的

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        //特殊情况判断
        List<List<Integer>> res = new LinkedList();
        if (nums == null || nums.length == 0){
            return res;
        }
        boolean [] isVisited = new boolean[nums.length];
        Deque<Integer> path = new ArrayDeque<Integer>();
        dfs(nums,0,path,res,isVisited);
        return res;
    }

    private void dfs(int[] nums, int depth, Deque<Integer> path, List<List<Integer>> res, boolean[] isVisited) {
        if (depth == nums.length){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i != 0 && nums[i] == nums[i - 1] && !isVisited[i - 1]) {
                continue;  // 防止重复
            }
            if (isVisited[i]){
                continue;
            }
            isVisited[i] = true;
            path.add(nums[i]);
            dfs(nums,depth + 1,path,res,isVisited);
            path.remove(nums[i]);
            isVisited[i] = false;
        }
    }
}
posted @ 2020-07-24 14:49  _未知的暖意  阅读(173)  评论(0编辑  收藏  举报