Leetcode Permutations II,本算法使用回溯法完成,本算法的关键是对于重复元素的处理,对于同一位置,同一元素不能出现超过两次,否则会导致后续元素重复。本算法,首先对数组进行排序,排序后对元素出现次数进行统计,后续进行迭代时,使用这一统计数组,保证递归时不在同一元素不在同一位置出现两次。相关cpp代码与测试如下:
#include<iostream>
#include<vector>
#include<algorithm>
/**
* This algorithm is just like the former one, but when we encounter the
* duplicate members which need to be specially deal with.
* First of all, we make a two demension array, and make each unique member
* an array of the two demension array. Each array hash two elements, the
* first is the number, and the second is the count.
* When we do recursive, we need to check every element make sure that every
* element which with count great than 0 can participate the iteration.
*/
using namespace std;
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int>& nums) {
vector<vector<int> > re;
if (nums.size() == 0) {
return re;
}
vector<vector<int> > unique_nums;
// Sort the nums for extract the duplicated members.
sort(nums.begin(), nums.end());
int count = 0;
unique_nums.push_back(vector<int>(2, 0));
unique_nums[count][0] = nums[0];
unique_nums[count][1] = 1;
// Statistic the duplicated members.
for (int i = 1; i < nums.size(); i ++) {
if (nums[i] != nums[i - 1]) {
count ++;
unique_nums.push_back(vector<int>(2, 0));
unique_nums[count][0] = nums[i];
}
unique_nums[count][1] ++;
}
vector<int> cur(nums.size(), 0);
backTrack(re, unique_nums, cur, 0, nums.size());
return re;
}
void backTrack(vector<vector<int> >& re, vector<vector<int> >& unique_nums,\
vector<int>& cur, int start, int size) {
if (start == size) {
re.push_back(cur);
return;
}
for (int i = 0; i < unique_nums.size(); i ++) {
// If the number the element great than 0, we can place it at this
// position.
if (unique_nums[i][1] != 0) {
cur[start] = unique_nums[i][0];
unique_nums[i][1] --;
backTrack(re, unique_nums, cur, start + 1, size);
unique_nums[i][1] ++;
}
}
}
};
// Sample input: ./a.out argv1 argv2....
int main(int argc, char* argv[]) {
Solution so;
vector<int> nums;
for (int i = 1; i < argc; i ++) {
nums.push_back(atoi(argv[i]));
}
vector<vector<int> > re = so.permuteUnique(nums);
cout<<"result: "<<endl;
for (int i = 0; i < re.size(); i ++) {
for (int j = 0; j < re[i].size(); j ++) {
cout<<re[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
input: 1 2 1
output:
1 1 2
1 2 1
2 1 1
input: 1 2 1 4
output:
1 1 2 4
1 1 4 2
1 2 1 4
1 2 4 1
1 4 1 2
1 4 2 1
2 1 1 4
2 1 4 1
2 4 1 1
4 1 1 2
4 1 2 1
4 2 1 1