Leetcode 47. Permutations II (Medium) (cpp)
2016-12-10 04:11
246 查看
Leetcode 47. Permutations II (Medium) (cpp)
Tag: Backtracking
Difficulty: Medium
/*
47. Permutations II (Medium)
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
*/
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> res;
permuteUnique(res, nums, 0);
return res;
}
private:
void permuteUnique(vector<vector<int>>& res, vector<int>& nums, int index) {
if (index == nums.size()) {
res.push_back(nums);
return;
}
unordered_set<int> s;
for (int i = index; i < nums.size(); i++) {
if (s.find(nums[i]) == s.end()) {
swap(nums[i], nums[index]);
permuteUnique(res, nums, index + 1);
swap(nums[i], nums[index]);
s.insert(nums[i]);
}
}
}
};
Tag: Backtracking
Difficulty: Medium
/*
47. Permutations II (Medium)
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
*/
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> res;
permuteUnique(res, nums, 0);
return res;
}
private:
void permuteUnique(vector<vector<int>>& res, vector<int>& nums, int index) {
if (index == nums.size()) {
res.push_back(nums);
return;
}
unordered_set<int> s;
for (int i = index; i < nums.size(); i++) {
if (s.find(nums[i]) == s.end()) {
swap(nums[i], nums[index]);
permuteUnique(res, nums, index + 1);
swap(nums[i], nums[index]);
s.insert(nums[i]);
}
}
}
};
相关文章推荐
- LeetCode-47-Permutations II(DFS/剪枝)-Medium
- 【LeetCode】47.Permutations II(Medium)解题报告
- [leetcode] 47.Permutations II
- leetcode 47. Permutations II 全排列问题(去掉重复元素)+递归
- Leetcode 162. Find Peak Element (Medium) (cpp)
- Leetcode 48. Rotate Image (Medium) (cpp)
- Leetcode 75. Sort Colors (Medium) (cpp)
- Leetcode 77. Combinations (Medium) (cpp)
- Leetcode 64. Minimum Path Sum (Medium) (cpp)
- Leetcode 79. Word Search (Medium) (cpp)
- LeetCode 47. Permutations II
- leetcode_middle_93_47. Permutations II
- Leetcode 61. Rotate List (Medium) (cpp)
- Leetcode 93. Restore IP Addresses (Medium) (cpp)
- Leetcode 221. Maximal Square (Medium) (cpp)
- leetcode 47. Permutations II
- Leetcode 54. Spiral Matrix (Medium) (cpp)
- Leetcode 74. Search a 2D Matrix (Medium) (cpp)
- Leetcode 47. Permutations II
- Leetcode 122. Best Time to Buy and Sell Stock II (Medium) (cpp)