题解 | #有重复项数字的全排列#
有重复项数字的全排列
https://www.nowcoder.com/practice/a43a2b986ef34843ac4fdd9159b69863
//在原有无重复排列的基础上,当拿出一个元素作第一个结点时,判断此元素与前一个元素的值是否相等,如果相等,这跳过次元素,进行下一个,即去重 #include <iostream> #include <algorithm> #include <vector> using namespace std; //class Solution { //public: void recursion(vector<vector<int>>& res, vector<int>& ans, vector<int>& vis, vector<int>& num) { if (ans.size() == num.size()) { res.push_back(ans); return; } for (int i = 0; i < num.size(); i++) { if (vis[i] == 1) { continue; } if (i > 0 && num[i] == num[i - 1] && vis[i - 1] == 1) { continue; } vis[i] = 1; ans.push_back(num[i]); recursion(res, ans, vis, num); ans.pop_back(); vis[i] = 0; } } vector<vector<int> > permuteUnique(vector<int>& num) { sort(num.begin(), num.end()); vector<vector<int>> res; vector<int> ans; vector<int> vis(num.size(), 0); recursion(res, ans,vis, num); return res; } int main() { int n; cin >> n; vector<int> num; int temp; for (int i = 0; i < n; i++) { cin >> temp; num.push_back(temp); } vector<vector<int>> end = permuteUnique(num); for (int i = 0; i < end.size(); i++) { for (int j = 0; j < n; j++) { cout << end[i][j] << ','; } cout << ' '; } } //};