LeetCode Permutations II
2014-06-28 10:28
411 查看
题目
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
和上一题类似,只是元素有重复。
不能单纯考虑元素是否和第一个相同,然后交换,如:1223,操作后会出现两个第一个元素为2的序列。
如果可交换数据区的第一个位置first到当前位置i中没有元素与当前位置i的相同,则交换,
即,交换每个不重复元素和重复元素中编号最小的一个。
代码:
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; } };
相关文章推荐
- Leetcode_permutations-ii
- LeetCode Permutations I && II
- [Leetcode]Permutations and Permuations II
- [Leetcode] #46#47 Permutations I & II
- leetcode Permutations II
- leetcode: Permutations/Permutations II
- [leetcode]47. Permutations II@Java解题报告
- LeetCode Permutations II
- LeetCode Permutations II
- LeetCode Permutations II
- LeetCode 46/47. Permutations i, ii
- leetcode — permutations-ii
- [LeetCode 46 & 47] Permutations I & II
- leetcode — permutations-ii
- leetcode46/47-Permutations I/II(全排列问题)
- 47. Permutations II leetcode
- LeetCode Permutations II
- LeetCode Permutations II
- 【LeetCode】Permutations & Permutations II & Next Permutations & Permutation Sequence
- [LeetCode] “全排列”问题系列(一) - 用交换元素法生成全排列及其应用,例题: Permutations I 和 II, N-Queens I 和 II,数独问题