ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode 47. Permutations II 全排列 II(中等)

2022-06-12 13:03:16  阅读:168  来源: 互联网

标签:tmp nums int 47 Permutations countMap perm II ans


一、题目大意

标签: 搜索

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

给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:

输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]

示例 2:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

提示:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

二、解题思路

用回溯法解决全排列问题,给定的数组中元素有重复,因此用回溯法执行后的全排列结果中会有重复的,如下图所示。

解决方法,先构造一个hashmap,key是元素,value是元素的个数,然后再用回溯法来解决

三、解题方法

3.1 Java实现

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        // 构造一个hashmap
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int n : nums) {
            int count = countMap.getOrDefault(n, 0);
            countMap.put(n, count + 1);
        }
        dfs(countMap, nums.length, new LinkedList<>(), ans);
        return ans;
    }

    void dfs(Map<Integer, Integer> countMap, int total, Deque<Integer> perm, List<List<Integer>> ans) {
        // 使用双端队列
        if (perm.size() == total) {
            ans.add(new ArrayList<>(perm));
        }
        for (Map.Entry<Integer, Integer> tmp : countMap.entrySet()) {
            if (tmp.getValue() > 0) {
                int oldValue = tmp.getValue();
                perm.offerFirst(tmp.getKey());
                tmp.setValue(tmp.getValue() - 1);
                dfs(countMap, total, perm, ans);
                tmp.setValue(oldValue);
                perm.pollFirst();
            }
        }
    }
}

四、总结小记

  • 2022/6/12 来记录结果的类型要用双端队列

标签:tmp,nums,int,47,Permutations,countMap,perm,II,ans
来源: https://www.cnblogs.com/okokabcd/p/16367784.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有