LeetCode47 Permutations II
来源:互联网 发布:苏州软件评测中心 编辑:程序博客网 时间:2024/06/05 20:52
原题:
英:
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,1,2], [1,2,1], [2,1,1]]
解题思路:
这道题是46题的变形,大体思路还是用递归,区别在于这里数组包含了重复值。在这里,我的思路是建立一个map,键值对就是数组中的树和出现的次数。在往列表中添加的时候,会用键值对进行比较,如果使用的次数小于出现的次数,那么可以添加,反之则不能。代码如下:
public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { int len = nums.length; Map<Integer,Integer> ans = new HashMap<Integer,Integer>(); for(int i :nums){ ans.put(i, ans.get(i)==null?1:ans.get(i)+1); //建一个键值对为数组中的数和出现次数的map } List<List<Integer>> res = new ArrayList(); List<Integer> add = new ArrayList<Integer>(); permuteRecursion(res, add,len, ans); return res; } private void permuteRecursion(List<List<Integer>> res, List<Integer> add, int len, Map<Integer, Integer> ans) { if(add.size()==len){ List<Integer> tmp = new ArrayList<Integer>(add); res.add(tmp); } for(int i :ans.keySet()){//这里不用nums[]进行循环了,因为会使得添加的list有重复 Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int m :add){ map.put(m, map.get(m)==null?1:map.get(m)+1); //使用次数的 } if(map.get(i)==null||map.get(i)<ans.get(i)){//使用次数与出现次数进行比较 add.add(i); permuteRecursion(res, add,len, ans); add.remove(add.size()-1); }else{continue;} } }}
重点说明:
1.我将nums数组转换成了键值对为数组中的数和出现次数的map。
2.循环使用map来完成,取代了nums[]。因为用nums[]循环的话,在list添加时会出现重复值。
3.在递归中,要建立一个map,用来记录当前list中存在的数和使用的次数。
4.将使用次数和出现次数进行比较,这里还要注意没用到当前数的情况,即:map.get(i)==null。
阅读全文
0 0
- [LeetCode47]Permutations II
- LeetCode47:Permutations II
- Leetcode47 Permutations II
- LeetCode47. Permutations II
- leetcode47. Permutations II
- LeetCode47 Permutations II
- leetcode47. Permutations II
- LeetCode47——Permutations II
- 递归——LeetCode47. Permutation II
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- Permutations and Permutations II
- Permutations && Permutations ii
- Permutations II
- Permutations II
- Permutations II
- liunx秘钥转换成ppk格式
- Android 内存优化总结
- 动态规划——洛谷1020_导弹拦截(1999年的)
- 工作上手
- 第4章 Java笔记 流程控制与数组
- LeetCode47 Permutations II
- 泛型类、泛型接口和泛型方法的使用定义
- 写给大数据开发初学者的话 | 附教程
- Tomcat Manager用户配置详解
- _changeDirection is not defined 报错
- 自建 java Lang String 类
- C++ 中 i++ 与 ++i 的本质区别
- CountdownView秒杀倒计时
- springboot thymeleaf eclipse热部署方案