题目链接
https://leetcode.com/problems/permutations-ii/
解题思路
dfs的时候每一层上的数字不要重复出现
代码
class Solution {
public:
void dfs(vector<vector<int>> &ans, vector<int> &nums, int ind) {
if (ind >= nums.size()) {
ans.push_back(nums);
}
unordered_set<int> set;
for (int i = ind; i < nums.size(); ++i) {
if (set.find(nums[i]) == set.end()) {
set.insert(nums[i]);
swap(nums[ind], nums[i]);
dfs(ans, nums, ind + 1);
swap(nums[ind], nums[i]);
}
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> ans;
dfs(ans, nums, 0);
return ans;
}
};
网友评论