47. Permutations II
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 code:
class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> v; sort(nums.begin(), nums.end()); recursion(nums, v, 0, nums.size()-1); return v; } void recursion(vector<int> nums, vector<vector<int>>& v, int i, int j) { if (i == j) { v.push_back(nums); return; } for (int k = i; k <= j; ++k) { if (i != k && nums[i] == nums[k]) continue; swap(nums[i], nums[k]); recursion(nums, v, i+1, j); } } };
Runtime: 28 ms, faster than 46.26% of C++ online submissions for Permutations II.
永远渴望,大智若愚(stay hungry, stay foolish)