We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = "abc" 输出:["abc","acb","bac","bca","cab","cba"]
限制:
考察排列的去重问题 解法一: 回溯法。难点在于如何去除重复。
class Solution { public: void backtracing(string s, set<string>& res, vector<int>& visited, string& tmp, int n) { if (tmp.size() == n) { res.insert(tmp); return; } for (int i = 0; i < n; i++) { if (!visited[i]) { tmp.push_back(s[i]); visited[i] = 1; backtracing(s, res, visited, tmp, n); tmp.pop_back(); visited[i] = 0; } } } vector<string> permutation(string s) { set<string> res; int n = s.size(); vector<int> visited(n, 0); string tmp = ""; backtracing(s, res, visited, tmp, n); vector<string> ans; for (auto r: res) { ans.push_back(r); } return ans; } };
解法二: 回溯法。排序去重。代码如下:
class Solution { public: void backtracing(string s, vector<string>& res, vector<int>& visited, string& tmp, int n) { if (tmp.size() == n) { res.push_back(tmp); return; } for (int i = 0; i < n; i++) { if (visited[i] || (i > 0 && s[i] == s[i-1] && !visited[i-1])) continue; tmp.push_back(s[i]); visited[i] = 1; backtracing(s, res, visited, tmp, n); tmp.pop_back(); visited[i] = 0; } } vector<string> permutation(string s) { vector<string> res; int n = s.size(); vector<int> visited(n, 0); string tmp = ""; sort(s.begin(), s.end()); backtracing(s, res, visited, tmp, n); return res; } };
Refer: 排列问题(二)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
限制:
考察排列的去重问题
解法一:
回溯法。难点在于如何去除重复。
问题就是效率太低。代码如下:
解法二:
回溯法。排序去重。代码如下:
Refer:
排列问题(二)
The text was updated successfully, but these errors were encountered: