Posted onEdited onInLeetCodeDisqus: Symbols count in article: 2.1kReading time ≈2 mins.
O(n*n!) time 先写 dfs 版本再写循环版本 先排序,对于每个位置,从小到大枚举之后的每个数(相同的数要跳过)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defpermuteUnique(self, nums: List[int]) -> List[List[int]]: nums.sort() res, n = [], len(nums) defdfs(A, b): if b == n: res.append(A) return for i inrange(b, n): if i > b and A[i] == A[b]: continue A[b], A[i] = A[i], A[b] dfs(A[:], b + 1) dfs(nums, 0) return res
voiddfs(vector<int> nums, int b){ // 注意nums是深拷贝 int n = nums.size(); if (b == n) { res.push_back(nums); } for (int i = b; i < n; ++i) { if (i > b && nums[i] == nums[b]) continue; // 去重 swap(nums[i], nums[b]); dfs(nums, b + 1); } }
classSolution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> res; do { res.push_back(nums); } while (next(nums)); return res; }
boolnext(vector<int> &A){ int n = A.size(); int x = 0, y = 0; for (int i = n - 1; i > 0; --i) { if (A[i - 1] < A[i]) { x = i - 1; y = i; break; } } if (y == 0) returnfalse; for (int i = n - 1; i > x; --i) { if (A[i] > A[x]) { swap(A[i], A[x]); break; } } reverse(A.begin() + y, A.end()); returntrue; } };