可先排序後,利用 next_permutation
解決此題。至於 next_permutation
如何實作可以看#LeetCode:31. Next Permutation這篇。
C++(20ms)
/*******************************************************/
/* LeetCode 47. Permutations II */
/* Author: Maplewing [at] knightzone.studio */
/* Version: 2019/04/14 */
/*******************************************************/
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> answer;
do{
answer.push_back(nums);
} while(next_permutation(nums.begin(), nums.end()));
return answer;
}
};