#include <vector> class Solution { public: vector<vector<int> > permuteUnique(vector<int> &num) { sort(num.begin(), num.end()); int n = num.size(); vector<vector<int> > res; vector<int> path; vector<int> visited(n, 0); path.reserve(n); function<void()> dfs = [&]() { if (path.size() == n) { res.push_back(path); return; } for (int i = 0; i < n; ++i) { if (visited[i] || i > 0 && num[i - 1] == num[i] && !visited[i - 1]) { continue; } visited[i] = 1; path.push_back(num[i]); dfs(); path.pop_back(); visited[i] = 0; } }; dfs(); return res; } };
思路:dfs搜索,去重剪枝。