[Leetcode] Permutations II
来源:互联网 发布:sqlserver 大数据处理 编辑:程序博客网 时间:2024/06/10 21:18
题目:
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]
.
思路:重点在如何避免冗余。比较trivial的一个做法是结果都放到set中,但是需要额外空间。观察题目中的例子可以看出冗余是如何形成的,对于第一个1,和自己swap后的结果为 1 1 2,按照Permuation I的做法,接下来和第二个1 swap,产生冗余结果。再看一个例子:[1, 2, 2]. 当1和第一个2 swap后,结果为 2 1 2,此时1再和后面的2 swap,产生 2 2 1. 但是,在 1 2 2 这步,如果1和第二个2直接swap,产生的结果还是 2 2 1,造成冗余。因此可以看到一个一般情况,对于数组AAAAAABBBBBBCCCCCC,假设当前位置为A,现在开始跟C交换,可以看到:A只需要跟第一个C交换,便可以产生和后面C交换同样的效果。换言之,每次需要交换的,从该元素开始,所有第一次出现的元素。需要注意的是,虽然之前做了排序,但数组在递归的过程中是乱序的,例如CAAAAABBBBBBACCCCC,当前元素为B. 因此不能通过 while (num[i] == num[i+1]) i++; 这样的简单方式判断,因为重复出现的元素可能不连续。
class Solution {public: void swap(int& a, int& b) { int temp = a; a = b; b = temp; } bool can_swap(const vector<int>& num, int start, int end) { //check duplicates for (; start < end; ++start) { if (num[start] == num[end]) return false; } return true; } void permute_helper(vector<int>& num, int pos, vector<vector<int>>& result) { if (pos == (int)num.size()) { //reach the end result.push_back(num); return; } for (int i = pos; i < (int)num.size(); ++i) { if (can_swap(num, pos, i)) { swap(num[pos], num[i]); permute_helper(num, pos + 1, result); swap(num[pos], num[i]); } } } vector<vector<int> > permuteUnique(vector<int> &num) { sort(num.begin(), num.end()); vector<vector<int>> result; permute_helper(num, 0, result); return result; }};
总结:复杂度为O(n!).
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- Leetcode: Permutations and Permutations II
- leetcode-permutations and permutations II
- Leetcode:Permutations与Permutations II
- LeetCode: Permutations II
- LeetCode Permutations II
- LeetCode: Permutations II
- [Leetcode] Permutations II
- [LeetCode] Permutations II
- [Leetcode] Permutations II
- leetcode Permutations II
- [LeetCode]Permutations II
- leetcode - Permutations II
- LeetCode-Permutations II
- [leetcode] Permutations II
- 富文本NSAttributedString与NSMutableAttributedString
- 血型统计
- 和支持向量机(SVM)相关的几个基本概念
- 优化网站设计(五):在顶部放置样式定义
- 我该何去何从?
- [Leetcode] Permutations II
- jQuery选中当前行
- Android—AlarmManager的使用
- 第十一周项目一(1)函数版星号图
- linux 中的find命令
- Unity3D获取外部摄像头图像
- 自己动手写CPU之第九阶段(5)——实现加载存储指令4(修改OpenMIPS顶层模块)
- 格式化存储装置成为 Ext2/Ext3/Ext4 档案系统
- 第十一周项目一 函数版星号图