leetcode Permutations II 无重全排列
2014-10-26 01:08
337 查看
作者:jostree 转载请注明出处 /article/7172702.html
题目链接:leetcode Permutations II 无重全排列
题目要求对有重复的数组进行无重全排列。为了保证不重复,类似于全排列算法使用dfs,将第一个数字与后面第一次出现的数字交换即可。例如对于序列1,1,2,2
有如下过程:
1,1,2,2 -> 1,1,2,2 -> 1,1,2,2 -> 1,1,2,2
-> 1,2,1,2 -> 1,2,1,2
-> 1,2,2,1
-> 2,1,1,2 -> 2,1,1,2 -> 2,1,1,2
-> 2,1,2,1
-> 2,2,1,1 -> 2,2,1,1
代码中使用set来记录数字是否在前面出现过,如果出现过,则不与第一个数字进行交换。
代码如下:
View Code
题目链接:leetcode Permutations II 无重全排列
题目要求对有重复的数组进行无重全排列。为了保证不重复,类似于全排列算法使用dfs,将第一个数字与后面第一次出现的数字交换即可。例如对于序列1,1,2,2
有如下过程:
1,1,2,2 -> 1,1,2,2 -> 1,1,2,2 -> 1,1,2,2
-> 1,2,1,2 -> 1,2,1,2
-> 1,2,2,1
-> 2,1,1,2 -> 2,1,1,2 -> 2,1,1,2
-> 2,1,2,1
-> 2,2,1,1 -> 2,2,1,1
代码中使用set来记录数字是否在前面出现过,如果出现过,则不与第一个数字进行交换。
代码如下:
class Solution { public: void swap(int &a, int &b) { int tmp = a; a = b; b = tmp; } void p(vector<int> &num, vector<vector<int> > &res, int begin) { if( begin == num.size() ) { vector<int> tmp; for( int i = 0 ; i < num.size() ; i++ ) { tmp.push_back(num[i]); } res.push_back(tmp); } else { set<int> used; for( int i = begin ; i < num.size() ; i++ ) { if(!used.count(num[i])) { used.insert(num[i]); swap(num[i], num[begin]); p(num, res, begin+1); swap(num[i], num[begin]); } } } } vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> >res; if( num.size() == 0 ) { return res; } sort(num.begin(), num.end()); p(num, res, 0); return res; } };
View Code
相关文章推荐
- “全排列”问题系列(一)[LeetCode] - 用交换元素法生成全排列及其应用,例题: Permutations I 和 II, N-Queens I 和 II,数独问题
- leetcode-46、47 Permutations/II 数字的排列组合
- [LeetCode] “全排列”问题系列(一) - 用交换元素法生成全排列及其应用,例题: Permutations I 和 II, N-Queens I 和 II,数独问题
- LeetCode (18) Permutations I & II (排列一、二)
- 【leetcode 排列组合问题】Next Permutation | Permutations | Permutations II | Permutation Sequence
- LeetCode解题报告—— Permutations & Permutations II & Rotate Image
- LeetCode Permutations II
- [leetcode 46] Permutations------数组中元素的所有排列组合集合
- LeetCode OJ Permutations II
- Leetcode Permutations II
- Leetcode Permutations II
- 46. 47. Permutations and Permutations II 都适用(Java,字典序 + 非字典序排列)
- Permutations 排序(有重复数)II @LeetCode
- 【LeetCode】667. Beautiful Arrangement II(优美的排列Ⅱ)
- LeetCode Permutations II (全排列)
- LeetCode:Permutations, Permutations II(求全排列)
- LeetCode Permutations II
- leetcode: Permutations/Permutations II
- 47. Permutations II leetcode
- leetcode46/47-Permutations I/II(全排列问题)