LeetCode Permutations II
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], And[2,1,1].
Ask for all sequences that are not repeated.
Train of Thought: dfs, but note that if deduplication: after sorting, you can set a vis for each number to indicate whether access has been made, when two adjacent numbers are the same and the previous one has been accessed, this number can be used to avoid duplication.
class Solution {public: int vis[110], a[110]; vector
> ans; void dfs(int cur, int n, vector
&num) { if (cur == n) { vector
tmp; for (int i = 0; i < n; i++) tmp.push_back(a[i]); ans.push_back(tmp); return; } for (int i = 0; i < n; i++) if (!vis[i]) { if (i != 0 && num[i] == num[i-1] && vis[i-1]) continue; vis[i] = 1; a[cur] = num[i]; dfs(cur+1, n, num); vis[i] = 0; } } vector
> permuteUnique(vector
&num) { sort(num.begin(), num.end()); ans.clear(); memset(vis, 0, sizeof(vis)); dfs(0, num.size(), num); return ans; }};