class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > vecs;
permutationUnique(vecs, num, 0);
return vecs;
}
void permutationUnique(vector<vector<int> > &vecs, vector<int> &num, int k)
{
if (k == num.size() - 1)
{
vecs.push_back(num);
}
else
{
for (int j = k; j < num.size(); ++j)
{
if (isSwap(k, j, num))
{
swap(num[k], num[j]);
permutationUnique(vecs, num, k + 1);
swap(num[k], num[j]);
}
}
}
}
//检查num[beg]至num[end]之间是否已出现过num[end], 有的话则不用交换
bool isSwap(int beg, int end, vector<int> &num)
{
bool res = true;
for (int i = end; i > beg; --i)
{
if (num[i - 1] == num[end])
{
res = false;
break;
}
}
return res;
}
};
LeetCode-Permutations II
最新推荐文章于 2024-11-09 21:51:15 发布