Work on the problem below as a puzzle algorithm. I wrote several similar solutions (and posted one of them below), tried it, and they worked. The question is, for the string โswap (num [i], num [k]);โ, how can we guarantee that we can always change the number that we have never tried before (for example, suppose we change 1 for 2 in the current iteration, the for loop, can we later change 2 back to 1 in the next iterations of the same for the cycle of the same level / level of the recursive call)? I have a confusion, since we pass num by reference, and it is very possible later (lower level / level) of recursive calls to modify the contents of the number, which leads to the fact that the numbers we have already evaluated swap back. However, I have tried and it works for all my test cases. Surprise,if the solution below is 100% correct, or happened with my test cases? :)
Below is a detailed report of the problem and the code I am debugging,
Given a set of numbers that may 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:
void recursion(vector<int> num, int i, int j, vector<vector<int> > &res) {
if (i == j-1) {
res.push_back(num);
return;
}
for (int k = i; k < j; k++) {
if (i != k && num[i] == num[k]) continue;
swap(num[i], num[k]);
recursion(num, i+1, j, res);
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
sort(num.begin(), num.end());
vector<vector<int> >res;
recursion(num, 0, num.size(), res);
return res;
}
};
thanks in advance Lin