47.全排列II
2018-11-02 本文已影响0人
HITZGD
题目
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:****
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
思路:
递归方法同46.全排列, 删除重复项的方法同40.组合总和II
#include <vector>
using namespace std;
class Solution {
private:
void swap (vector<int>& nums, int begin, int end)
{
int temp = nums[begin];
nums[begin] = nums[end];
nums[end] = temp;
}
void findPermuteUnique(vector<int>& nums, vector<vector<int>>& result, int begin, int end)
{
if(begin == end)
{
vector<vector<int>>::iterator flag;
flag = find(result.begin(), result.end(), nums);
if (flag == result.end())
{
result.push_back(nums);
return;
}
}
for(int i = begin; i <= end; i ++)
{
swap(nums, i, begin);
findPermuteUnique(nums, result, begin + 1, end);
swap(nums, i, begin);
}
}
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> result;
vector<int> temp;
int end = nums.size() - 1;
findPermuteUnique(nums, result, 0, end);
return result;
}
};
int main(int argc, char* argv[])
{
vector<int> test = {1, 1, 2};
auto res = Solution().permuteUnique(test);
return 0;
}