LeetCode Permutations II
来源:互联网 发布:淘宝海报尺寸一般多少 编辑:程序博客网 时间:2024/04/29 18:08
题目
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]
.
和上一题类似,只是元素有重复。
不能单纯考虑元素是否和第一个相同,然后交换,如:1223,操作后会出现两个第一个元素为2的序列。
如果可交换数据区的第一个位置first到当前位置i中没有元素与当前位置i的相同,则交换,
即,交换每个不重复元素和重复元素中编号最小的一个。
代码:
class Solution {vector<vector<int>> ans;public: void innerPermuteUnique(vector<int> &num,int first){int len=num.size();int i,j;if(first==len){ans.push_back(num);return;}for(i=first;i<len;i++){for(j=first;j<i;j++)//只交换没有出现过的元素,使用二叉树速度会更快一些if(num[i]==num[j])break;if(j<i)continue;swap(num[first],num[i]);innerPermuteUnique(num,first+1);swap(num[first],num[i]);}}vector<vector<int> > permuteUnique(vector<int> &num) { ans.clear();innerPermuteUnique(num,0);return ans; }};
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
- 【JOB】
- MP及OMP算法
- Median of Two Sorted Arrays
- android:layout_gravity和android:gravity的区别
- JNDI 的理解
- LeetCode Permutations II
- 阅读 mongodb 副本集的 笔记
- 数字快速幂(模板)
- signal 是mysql的关键字
- PendingIntent用法
- Android应用程序的编译和打包
- ie6下的js调试工具companion.js
- C3P0数据库连接池【JAVA】-oracle数据库为例
- 7.解决谷歌的SDK更新失败问题。