[LeetCode] Permutations II
来源:互联网 发布:动力学分析软件 编辑:程序博客网 时间:2024/05/16 12:21
问题:
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]
.
这道题跟上一道题相似(点击这里)。但出现了重复元素这件事我们得小心一点。处理的方法是:每一次跟后面的元素swap之前,先检查一下后面这个元素之前是不是出现过。如果出现过,则continue;否则才交换。
代码(O(n!)):
class Solution {public:bool already_swaped(int index, int i, const vector<int> &num) {for (int j = index; j < i; j ++) {if (num[j] == num[i])return true;}return false;}vector<vector<int> > permuteUnique(vector<int> &num) {vector<vector<int> > result;if (num.size() == 0)return result;permuteHelper(num, result, 0);return result;}void permuteHelper(vector<int> &num, vector<vector<int> > & result, int index) {if (index == num.size()) {result.push_back(num);return;}for (int i = index; i < num.size(); i ++) {if (already_swaped(index, i, num)) continue;int temp = num[i];num[i] = num[index];num[index] = temp;permuteHelper(num, result, index + 1);num[index] = num[i];num[i] = temp;}}};
0 0
- 【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
- hadoop-入门
- php main 与 iframe 相互通讯类(同域/跨域)
- [LeetCode] Permutations
- get COM interface method address .
- 【Java.Web】创建一个简单的Java Web项目
- [LeetCode] Permutations II
- AS函数复习
- 直接插入排序
- c# 异常找不到源代码的情况
- [cocos2dx]随机数的使用
- 模拟器设计--未完待续
- DP32 单词按照字典分割问题 Word Break Problem @geeksforgeeks
- Android学习第二天——Intent & Activity的生命周期
- android notification 应用123