- 题目:输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
- 思路
- 一波DFS操作,排列出了所有的字符串
- 启发或者坑
- 结果集需要去重才行
- DFS遍历需要能返回到前一状态,类似于八皇后
- 代码
class Solution { public: vector<string> res; map<string, int> mark; vector<string> Permutation(string str) { if (str=="") return res; findAll(str, ""); sort(res.begin(), res.end()); return res; } void findAll(string str, string oneres) { if (str.length() == 0) { map<string, int>::iterator iter; iter = mark.find(oneres); if(iter == mark.end()) { mark.insert(pair<string, int>(oneres, 1)); res.push_back(oneres); return; } } for(int i = 0; i < str.length(); i++) { string str_copy = str; string str_char = str.substr(i, 1); str.erase (i,1); findAll(str, oneres+str_char); str = str_copy; } } };
剑指offer 29.字符串的排列
最新推荐文章于 2021-09-05 20:53:03 发布