题解 | #字符串的排列#
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
#include <iterator> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return string字符串vector */ void backtrace(string str, string current, vector<string> &res, vector<bool> &used) { int n1 = str.length(), n2 = current.length(); if(n1 == n2) { res.push_back(current); return; } for(int i = 0; i < n1; ++i) { if(used[i] || (i > 0 && str[i] == str[i - 1] && !used[i - 1])) continue; used[i] = true; current += str[i]; backtrace(str, current, res, used); used[i] = false; current.pop_back(); } } vector<string> Permutation(string str) { if(str == "") return {}; string current = ""; vector<string> res; int n = str.length(); vector<bool> used(n, false); sort(str.begin(), str.end()); backtrace(str, current, res, used); return res; } };
跟有重复数字的数列的全排列是一个思路,不多说了