首页 > 代码库 > LeetCode Permutations II
LeetCode Permutations II
class Solution { public: vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > result; if (num.size() < 1) return result; vector<int> path; dfs(num, 0, path, result); } void dfs(vector<int>& dict, int pos, vector<int>& path, vector<vector<int> > &result) { int len = dict.size(); if (pos >= len) { result.push_back(path); return; } unordered_set<int> uniques; for (int i=pos; i<len; i++) { if (i != pos && uniques.count(dict[i]) > 0) continue; uniques.insert(dict[i]); path.push_back(dict[i]); int tmp = dict[i]; dict[i] = dict[pos]; dict[pos] = tmp; dfs(dict, pos + 1, path, result); path.pop_back(); tmp = dict[i]; dict[i] = dict[pos]; dict[pos] = tmp; } } };
也可以用next_permutation
class Solution { public: vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > res; sort(num.begin(), num.end()); do { res.push_back(num); } while (next_permutation(num.begin(), num.end())); return res; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。