首页 > 其他 > 详细

47. 全排列 II Permutations II

时间:2020-12-23 15:06:24      阅读:24      评论:0      收藏:0      [点我收藏+]

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

 

方法:

回溯法,去重

 

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);
        }
    }

 

参考链接:

https://leetcode.com/problems/permutations-ii/

https://leetcode-cn.com/problems/permutations-ii/

47. 全排列 II Permutations II

原文:https://www.cnblogs.com/diameter/p/14178151.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!