题解 | #字符串的排列#
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
#include <bits/stdc++.h> using namespace std; #include <stack> class Solution { public: set<string> res; void dfs( string str, string tmp, vector<bool> &vis ) { if (tmp.size() == str.size()) { res.insert(tmp); return; } for (int i = 0; i < str.length(); i++) { //如果未选择 if (vis[i] == false) { vis[i] = true; dfs( str,tmp + str[i], vis ); vis[i] = false; } } } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return string字符串vector */ vector<string> Permutation(string str) { vector<bool>vis(str.length(),false); vector<string>res_vec; dfs( str, "", vis); for (auto it = res.begin(); it != res.end(); it++) { res_vec.push_back(*it); } return res_vec; } };
这牛客啥时候编程和leetcode一样的模式了?
两个问题:
使用vector,不用数组
传参如果需要改变,使用引用传参
可以使用类属性set<string> res;因为它不需要初始化,像 vector<bool>vis(str.length(),false); 需要字符串长度初始化