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);
                }
            }
        }
  • 相关阅读:
    项目经验分享(上)
    socket.io实现在线群聊
    socket.io中文文档
    常用的Sublime Text插件及安装方法
    常用的Atom插件
    atom及其插件activate-power-mode下载安装
    jeesite快速开发平台
    js权威指南
    hexSHA1散列加密解密(不可逆)
    腾讯云企业邮箱
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4535198.html
Copyright © 2011-2022 走看看