LeetCode 47. 全排列 II

在这里插入图片描述
官方

class Solution {
    boolean[] vis;
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> perm = new ArrayList<Integer>();
        vis = new boolean[nums.length];
        Arrays.sort(nums);
        backtrack(nums, ans, 0, perm);
        return ans;
    }

    public void backtrack(int[] nums, List<List<Integer>> ans, int idx, List<Integer> perm){
        if(idx == nums.length){
            ans.add(new ArrayList<Integer>(perm));
            return;
        }
        for(int i = 0; i < nums.length; i++){
            if(vis[i] || (i > 0 && nums[i] == nums[i - 1] && !vis[i - 1])){
                continue;
            }
            perm.add(nums[i]);
            vis[i] = true;
            backtrack(nums, ans, idx + 1, perm);
            vis[i] = false;
            perm.remove(idx);
        }
    }
}
//写法二:用set剪纸
class Solution {
    boolean[] vis;
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> perm = new ArrayList<Integer>();
        vis = new boolean[nums.length];
        Arrays.sort(nums);
        backtrack(nums, ans, 0);
        return ans;
    }

    public void backtrack(int[] nums, List<List<Integer>> ans, int idx){
        if(idx == nums.length){
            ans.add(Arrays.stream(nums).boxed().collect(Collectors.toList()));
            return;
        }
        HashSet<Integer> set = new HashSet<Integer>();
        for(int i = idx; i < nums.length; i++){
            if(set.contains(nums[i]))
                continue;
            set.add(nums[i]);
            swap(nums, i, idx);
            backtrack(nums, ans, idx + 1);
            swap(nums, i, idx);
        }
    }

    private void swap(int[] nums, int i, int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页