题解 | #字符串的排列#
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
#include <type_traits> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return string字符串vector */ void dfs(int h, string s, set<string> &ans) { if (h == s.size() - 1) { ans.insert(s); return; } for (int i = h; i < s.size(); ++i) { swap(s[i], s[h]); dfs(h+ 1, s, ans); swap(s[i], s[h]); } } vector<string> Permutation(string str) { // write code here if (str.empty()) return {}; set<string> ans; dfs(0, str, ans); return vector<string>({ans.begin(), ans.end()}); } };
全排列 , 可以用深度优先搜索的方式去做;
dfs中的任务就是不断的交换不同位置上的字符串
这里面有个比较关键的地方: 用set来存放string