您的位置:首页 > 其它

[leetcode 47] Permutations II

2015-01-11 11:22 555 查看
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]
.

class Solution {
public:
vector< vector<int> > res;
int N;
vector<vector<int> > permuteUnique(vector<int> &num) {
N = num.size();
res.clear();
sort(num.begin(),num.end());
perm(num,0);
return res;
}
bool isSwap(vector<int>& num, int s, int e) {
int i = s;
while (num[i] != num[e] && i < e) i++;
if (i == e) return true;
else return false;
}
void perm(vector<int> &num, int i) {
if (i == N-1) {
res.push_back(num);
return ;
}
for (int j = i; j < N; j++) {
if (!isSwap(num, i, j)) continue;
swap(num[i],num[j]);
perm(num,i+1);
swap(num[i],num[j]);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: