zoukankan      html  css  js  c++  java
  • Permutations II ——LeetCode

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

    For example,
    [1,1,2] have the following unique permutations:
    [1,1,2][1,2,1], and [2,1,1].

    题目大意:给一个数组,包含重复元素,返回所有可能组合,去重。

    解题思路:这题是Permutation的变种,思路就是回溯。首先把数组排序一下,对于不是第一次使用的数字,检测是否出现过。

        public List<List<Integer>> permuteUnique(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            if (nums == null || nums.length == 0) {
                return res;
            }
            Arrays.sort(nums);
            List<Integer> tmp = new ArrayList<>();
            boolean[] used = new boolean[nums.length];
            helper(res, tmp, 0, nums.length, nums, used);
            return res;
        }
    
        public void helper(List<List<Integer>> res, List<Integer> tmp, int n, int N, int[] nums, boolean[] used) {
            if (n == N) {
                res.add(new ArrayList<>(tmp));
                return;
            }
            int last_num = 0x80000000;
            for (int i = 0; i < N; i++) {
                if (!used[i] && last_num != nums[i]) {
                    used[i] = true;
                    tmp.add(nums[i]);
                    last_num = nums[i];
                    helper(res, tmp, n + 1, N, nums, used);
                    used[i] = false;
                    tmp.remove(tmp.size() - 1);
                }
            }
        }
  • 相关阅读:
    Spring Boot + Vue 开发前后端分离的员工管理系统
    树莓派4B部署docker
    免费的论文查重网站
    JavaScript设计模式
    js继承的用法
    js闭包与柯里化
    Javascript编程小技巧
    spy-debugger和fiddler实现移动端抓包
    grid布局
    js判断对象是否为空对象的几种方法
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4535198.html
Copyright © 2011-2022 走看看