LeetCode (Permutations II)

xiaoxiao2021-02-27  511

Problem:

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] ] Solution:

class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> ans; if (nums.empty() || nums.size() == 1) return {nums}; vector<int> num = nums; num.erase(num.begin()); vector<vector<int>> temp = permuteUnique(num); for (int i = 0; i < temp.size(); i++){ for (int j = 0; j < nums.size(); j++){ vector<int> p = temp[i]; if (j > 0 && nums[0] == p[j - 1]) continue; else p.insert(p.begin() + j, nums[0]); if (find(ans.begin(), ans.end(), p) == ans.end()) ans.push_back(p); } } return ans; } };

转载请注明原文地址: https://www.6miu.com/read-1239.html

最新回复(0)