题解 | #牛牛的字符串排列#
牛牛的字符串排列
https://www.nowcoder.com/practice/5286dafdcdff4c9a9e92c7dc440143db
#include <any>
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param k int整型
* @return string字符串vector
*/
void swap(string& s, int a , int b){
if (a == b) return;
char temp = s[b];
memcpy(&s[a+1], &s[a], sizeof(char)*(b-a));
s[a] = temp;
return;
}
void rswap(string& s, int a , int b){
if (a == b) return;
char temp = s[a];
memcpy(&s[a], &s[a+1], sizeof(char)*(b-a));
s[b] = temp;
return;
}
void back(vector<string>& res, string& str, string& s, int k, int index){
if (str.size() == s.size()){
res.push_back(str);
return;
}
for(int i = index; i < s.size(); ++i){
// 第一次选择 选择第几个
str.push_back(s[i]);
swap(s, index, i);
back(res, str, s, k, index+1);
str.pop_back();
rswap(s, index, i);
if (res.size() == k) return;
}
return;
}
vector<string> getPermutation(string s, int k) {
// write code here
vector<string> res;
string str;
sort(s.begin(), s.end());
// cout << s;
back(res, str, s, k, 0);
return res;
}
};
上海得物信息集团有限公司公司福利 1188人发布