LeetCode Algorithms 47. Permutations II
来源:互联网 发布:知满天教育官网 编辑:程序博客网 时间:2024/06/05 13:34
题目难度: Medium
原题描述:
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], [2,1,1]]
题目大意:
给你若干个可能会有重复的数,要求返回这些数的所有不重复的排列。
解题思路:
这道题和普通的全排列问题的区别在于,数可能会有重复,如果有重复的话,就要考虑如何去除重复的排列。看到这道题后,我想到的第一种方法就是直接枚举所有排列,并将每一个排列加入HashMap中,利用HashMap去除重复的排列。但是这种方法的问题在于,空间复杂度达到了和时间复杂度一样的O(n!),空间消耗太大。
后来想到的第二种方法是,首先对原数组进行排序,然后再统计原数组中每个数出现的次数,作为后面算法的预处理。在算法的主体中,当在第cur层填写数时,枚举原数组中的每一个数nums[i],当nums[i]在原数组出现的次数大于在第cur层之前填写过的数出现的次数时,才把该数填写在第cur层上。这样就能将重复的排列去掉。这种算法的空间复杂度仅为O(n)。
时间复杂度分析:
由于总的排列数是n!,n为一个排列里数的个数,因此总的时间复杂度为O(n!)。
以下是代码:
public class Solution { private static List<List<Integer>> ans = new ArrayList< List<Integer> >();private static Map<Integer, Integer> numsMap = new HashMap<Integer, Integer>();private static Map<Integer, Integer> pMap = new HashMap<Integer, Integer>();private void dfs(int[] nums , int cur , Integer[] p){if(cur >= nums.length){ans.add( new ArrayList<Integer>(Arrays.asList(p)) );return;}for(int i=0 ; i<nums.length ; ++i){if(i==0 || (i>0 && nums[i]!=nums[i-1])){if(numsMap.get(nums[i]) > pMap.get(nums[i])){p[cur] = nums[i];pMap.replace(nums[i], pMap.get(nums[i])+1);dfs(nums, cur+1, p);pMap.replace(nums[i], pMap.get(nums[i])-1);}}}}public List<List<Integer>> permuteUnique(int[] nums) { ans.clear(); numsMap.clear(); pMap.clear();Integer[] p = new Integer[nums.length];Arrays.sort(nums);for(int i=0 ; i<nums.length ; ++i){if(numsMap.containsKey(nums[i])){numsMap.replace(nums[i], numsMap.get(nums[i])+1);}else{numsMap.put(nums[i], 1);}if(!pMap.containsKey(nums[i])){pMap.put(nums[i], 0);}}dfs(nums, 0, p);return ans; }}
阅读全文
0 0
- LeetCode-algorithms 47. Permutations II
- LeetCode Algorithms 47. Permutations II
- [LeetCode]47.Permutations II
- LeetCode 47.Permutations II
- LeetCode --- 47. Permutations II
- [Leetcode] 47. Permutations II
- [leetcode] 47.Permutations II
- LeetCode 47. Permutations II
- 47. Permutations II LeetCode
- Leetcode 47. Permutations II
- LeetCode 47. Permutations II
- LeetCode - 47. Permutations II
- [LeetCode] 47. Permutations II
- leetcode 47. Permutations II
- [LeetCode]--47. Permutations II
- [LeetCode]--47. Permutations II
- [leetcode] 47. Permutations II
- leetcode 47. Permutations II
- win10系统jdk1.8降为jdk1.6
- NYOJ 199 无线网络覆盖
- [leetcode]: 112. Path Sum
- 用户自定义函数
- 线程学习1--pthread_create
- LeetCode Algorithms 47. Permutations II
- 安装anaconda2
- leetcode_153. Find Minimum in Rotated Sorted Array
- java的多态
- 离散数学知识框架小结
- Linux查看DNS
- 硬币排成线I和硬币排成线II问题
- cntk深度网络——从入门到转行一
- React native 技术中 android 和 iOS 平台差异