mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
57 lines
2.0 KiB
Markdown
57 lines
2.0 KiB
Markdown
# [47. Permutations II](https://leetcode.com/problems/permutations-ii/)
|
||
# 思路
|
||
有了[31. Next Permutation](https://leetcode.com/problems/next-permutation/)和[46. Permutations](https://leetcode.com/problems/permutations/)的做题经验,这题就显得是一个送分题了。
|
||
这题与46题唯一区别就是此题允许重复元素,所以需要注意在元素比较的时候相等的情况。参考[46的题解](https://github.com/ShusenTang/LeetCode/blob/master/solutions/46.%20Permutations.md)即可很容易写出代码。
|
||
|
||
|
||
# C++
|
||
## 使用STL中的next_permutations(完全同46题)
|
||
``` C++
|
||
class Solution {
|
||
public:
|
||
vector<vector<int>> permuteUnique(vector<int>& nums) {
|
||
vector<vector<int>>res;
|
||
if(nums.empty()) return res;
|
||
sort(nums.begin(), nums.end()); // 先排序
|
||
res.push_back(nums);
|
||
while(next_permutation(nums.begin(), nums.end())) res.push_back(nums);
|
||
return res;
|
||
}
|
||
};
|
||
```
|
||
## 手动实现
|
||
``` C++
|
||
class Solution {
|
||
private:
|
||
bool my_next_permute(vector<int>& nums){
|
||
int len = nums.size();
|
||
int i = len - 1;
|
||
while(i > 0 && nums[i] <= nums[i - 1]) i--; // 与46题的不同点一
|
||
if(i == 0) return false;
|
||
|
||
int mid, low = i, high = len - 1;
|
||
while(low <= high){ // 二分查找
|
||
mid = low + (high - low) / 2;
|
||
if(nums[mid] <= nums[i - 1]) high = mid - 1; // 与46题的不同点二
|
||
else low = mid + 1;
|
||
}
|
||
|
||
// int high = len - 1;
|
||
// while(nums[i - 1] >= nums[high]) high--; // 与46题的不同点二
|
||
|
||
swap(nums[i - 1], nums[high]);
|
||
reverse(nums.begin() + i, nums.end());
|
||
return true;
|
||
}
|
||
public:
|
||
vector<vector<int>> permuteUnique(vector<int>& nums) {
|
||
vector<vector<int>>res;
|
||
if(nums.empty()) return res;
|
||
sort(nums.begin(), nums.end()); // 先排序
|
||
res.push_back(nums);
|
||
while(my_next_permute(nums)) res.push_back(nums);
|
||
return res;
|
||
}
|
||
};
|
||
```
|