1.全排列的重点在于各字母出现的频数而不是对字符串的调整。以回溯的方式,通过操作字母表的频数和当前string的位数来实现全排列。
2.可以采用递归法或STL。
3.STL中已经有轮子--bool next_permutation(itr1,itr2),此算法需要配合sort()使用。
以下是原文: <转自:http://www.cnblogs.com/lanxuezaipiao/p/3299601.html>
#include <stdio.h>
int t[200];
char s[200];
int n = 0;
void permutation(int i)
{
int k;
// a~z的ASCII码在97到122之间
for(k = 97; k < 123; k++)
{
if(t[k])
{
t[s[i] = k]--;
permutation(i + 1);
t[k]++;
}
}
// 只有n个字母全部排好了才输出
n - i || puts(s);
}
int main()
{
int i;
puts("Please Input letter sequence: ");
gets(s);
// t[]记录每个字母的出现频率
// n为待排序列的长度
for(i = 0; s[i] != '\0'; i++)
{
t[s[i]]++;
n++;
}
puts("Permutation result: ");
permutation(0);
return 0;
}
方法二:STL法
C++的STL有一个函数可以方便地生成全排列,这就是next_permutation
在C++ Reference中查看了一下next_permutation的函数声明:
#include <algorithm>
bool next_permutation( iterator start, iterator end );
The next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.
从说明中可以看到 next_permutation 的返回值是布尔类型。按照提示写了一个标准C++程序:
其中用到了 sort 函数,如果不先排序,则完成不了全排列。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
cout << "Please Input letter sequence: \n";
cin >> str;
// 必须先排序
sort(str.begin(), str.end());
cout << str << endl;
cout << "Permutation result: \n";
while(next_permutation(str.begin(), str.end()))
{
cout << str << endl;
}
return 0;
}
在使用稍大数据测试的时候,发现标准C++的效率很差,换成C函数写一下,效率提升了许多倍,比如我用字符序列“aabbddef”作为测试,上面C++代码用了6s,而下面的C代码只用了0.918s。所以,平时写代码时能用C就用C。