题目链接:47.permutations-ii
相比全排列,多了重复数字的干扰,可以参照带重复数字的组合问题来进行去重:if (used[i] == 1)
判断nums[i]
是否已经在path
中,if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0)
来进行去重。
注意,要先对目标数组排序。
#include <vector>
#include <algorithm>
using std::vector;
class Solution {
private:
vector<int> path;
vector<vector<int>> res;
int used[8] = {0};
void track_back(vector<int> nums, int index) {
if (path.size() >= nums.size()) {
res.push_back(path);
return;
}
for (int i = 0; i < nums.size(); i++) {
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0)
continue;
if (used[i] == 1)
continue;
path.push_back(nums[i]);
used[i] = 1;
track_back(nums, 0);
path.pop_back();
used[i] = 0;
}
return;
}
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
std::sort(nums.begin(), nums.end());
track_back(nums, 0);
return res;
}
};
标签:used,nums,47,permutations,back,ii,vector,&&,path
From: https://www.cnblogs.com/zwyyy456/p/16716847.html