字符串的全排列是面试中相对而言必要重要的算法,有两种实现方法:递归,非递归
补充:
替换点:从字符串的最后一位开始,找到第一个逆序的字符串,如“54312”那么从后向前第一个逆序为12,那个1就是替换值,替换值得位置就是替换点。
非递归方式:
非递归算法思想:
- 对字符串进行从小到大排序,这个可以最快的从后向前找到替换点,找到第一个替换点,记录位置为replace_pos
- 找到替换点之后比它大的最小的数,然后两个数互换位置
- 把replace_pos后的数进行翻转,便可以得到一个排列输出
- 依次循环执行上面三个步骤,直到找不到替换点,说明排列组合输出完毕
对于一个字符串4231,这个字符串中排列组合中1234是最小的数,4321是最大的数,上面的算法步骤就是输出从1234-4321的一个有序数组队列。
算法代码实现
#include <iostream>
#include <string>
#include <algorithm>
#include <string.h>
#include <vector>
bool find_replace_pos(const std::string& str, size_t& rp, size_t& min_max) {
rp = str.size() - 1;
min_max = std::string::npos;
while (rp >= 0) {
for (size_t b = rp; b < str.size(); ++b) {
if (str[b] > str[rp]) { //逆序
if (min_max == std::string::npos) {
min_max = b;
} else {
if (str[min_max] > str[b]) {
min_max = b;
}
}
}
}
if (min_max != std::string::npos) {
return true;
}
if (rp == 0) {
return false;
}
--rp;
}
return false;
}
void swap(std::string& str, size_t from, size_t to) {
if (from == to) {
return;
}
std::string::value_type tmp = str.at(from);
str[from] = str.at(to);
str[to] = tmp;
}
void reverse(std::string& str, size_t start, size_t end) {
size_t st = start;
size_t et = end;
while ((st < et) && (et != std::string::npos)) {
swap(str, st, et);
st++;
et--;
}
}
void permutation(std::string str, std::vector<std::string>& ret) {
if (str.empty()) {
return;
}
size_t end = str.size() - 1;
size_t rp = std::string::npos;
size_t min_max = std::string::npos;
std::sort(str.begin(), str.end());
ret.push_back(str);
while (find_replace_pos(str, rp, min_max)) {
swap(str, rp, min_max);
reverse(str, rp + 1, end);
ret.push_back(str);
}
}
int main()
{
std::string str("123456");
std::vector<std::string> ret;
permutation(str, ret);
for (size_t index = 0; index < ret.size(); ++index) {
std::cout << ret[index] << std::endl;
}
std::cout << "ret size:" << ret.size() << std::endl;
return 0;
}
递归方式:
递归算法思想:
一个字符串有N个字符串,那个全排列的定义本身就是一个递归定义(在不考虑重复字符时),N个字符一次固定在首位排列组合*剩余N-1个字符串的排列组合。
#include <iostream>
#include <string>
#include <algorithm>
#include <string.h>
#include <vector>
void swap(std::string& str, size_t from, size_t to) {
if (from == to) {
return;
}
std::string::value_type tmp = str.at(from);
str[from] = str.at(to);
str[to] = tmp;
}
// 递归方法
// permutation(n)
void permutation(std::string& str, size_t start, size_t end, std::vector<std::string>& ret) {
if (start == end - 1) {
ret.push_back(str);
return;
}
for (size_t index = start; index < end; ++index) {
swap(str, start, index);
//permutation(n-1)
permutation(str, start + 1, end, ret);
swap(str, start, index);
}
}
int main()
{
std::string str("123456");
std::vector<std::string> ret;
// 递归方法
permutation(str, 0, str.size(), ret);
for (size_t index = 0; index < ret.size(); ++index) {
std::cout << ret[index] << std::endl;
}
std::cout << "ret size:" << ret.size() << std::endl;
return 0;
}