您的位置:首页 > 其它

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,

[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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: