Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
AC代码
void digui(vector<int>& nums, vector<int>& t, map<int, int>& mp,
vector<vector<int>>& ans) {
if (t.size() == nums.size()) {
ans.push_back(t);
return;
}
for (int i = 0; i < nums.size(); ++i) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
if (mp[nums[i]] > 0) {
mp[nums[i]]--;
t.push_back(nums[i]);
digui(nums, t, mp, ans);
t.pop_back();
mp[nums[i]]++;
}
}
}
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> t;
map<int, int> mp;
for (int i = 0; i < nums.size(); ++i) mp[nums[i]]++;
sort(nums.begin(), nums.end());
digui(nums, t, mp, ans);
return ans;
}
};
总结
有点找到深度优先搜索的感觉了
网友评论