【DFS】LeetCode 47. 全排列 II

题目链接

47. 全排列 II

思路

借用代码随想录的图。

image

以最右侧的分支为例,首先将 2 摆在第一位,剩下两个 1,在走完左边的 1 分支之后,对右边的 1 进行判断,发现右边的 1 还是和左边的一样,摆在第二个位置上(因为 used[i - 1] == false,说明左边的 1 没有使用)。因此判断出两个树枝搜索出的结果是相同的,进行剪枝。

代码

class Solution {
    private List<List<Integer>> result = new ArrayList<>();
    private Deque<Integer> path = new ArrayDeque<>();
    private boolean[] used;

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        used = new boolean[nums.length];

        dfs(nums);

        return result;
    }

    void dfs(int[] nums){
        if(path.size() == nums.length){
            result.add(new ArrayList<>(path));
            return;
        }

        for(int i = 0; i < nums.length; i++){
            if(i != 0 && nums[i - 1] == nums[i] && !used[i - 1]){
                continue;
            }
            if(!used[i]){
                path.addLast(nums[i]);
                used[i] = true;
                dfs(nums);
                used[i] = false;
                path.removeLast();
            }
        }
    }
}
posted @ 2023-03-06 14:31  Frodo1124  阅读(19)  评论(0编辑  收藏  举报