题解 | #字符串的排列#
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; //class Solution { //public: void recursion(vector<string> &res,string str,vector<char> &ans,vector<int> vis) { if (ans.size() == str.length()) { string rans(ans.begin(), ans.end()); res.push_back(rans); return; } for (int i = 0; i < str.length(); i++) { if (vis[i] == 1) continue; if (i > 0 && str[i] == str[i - 1] && vis[i - 1] == 1) { continue; } vis[i] = 1; ans.push_back(str[i]); recursion(res, str, ans, vis); vis[i] = 0; ans.pop_back(); } } vector<string> Permutation(string str) { sort(str.begin(), str.end()); vector<char> ans; vector<string> res; vector<int> vis(str.length(), 0); recursion(res, str, ans, vis); return res; } int main() { string str; cin >> str; vector<string> res = Permutation(str); for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res[i].size(); j++) { cout << res[i][j]; } cout << ' '; } return 0; } //};