全排列算法的实现
来源:互联网 发布:ubuntu开机启动脚本 编辑:程序博客网 时间:2024/06/04 18:44
用C++写一个函数, 如 Foo(const char *str), 打印出 str 的全排列,
如 abc 的全排列: abc, acb, bca, dac, cab, cba
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++程序:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
sort(str.begin(), str.end());
cout << str << endl;
while (next_permutation(str.begin(), str.end()))
{
cout << str << endl;
}
return 0;
}
其中还用到了 sort 函数和 string.begin()、string.end() ,函数声明如下:
#include <algorithm>
void sort( iterator start, iterator end );
sort函数可以使用NlogN的复杂度对参数范围内的数据进行排序。
#include <string>
iterator begin();
const_iterator begin() const;
#include <string>
iterator end();
const_iterator end() const;
string.begin()和string.end() 可以快速访问到字符串的首字符和尾字符。
在使用大数据测试的时候,发现标准C++的效率很差...换成C函数写一下,效率提升了不止一倍...
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX 100
using namespace std;
int main()
{
int length;
char str[MAX];
gets(str);
length = strlen(str);
sort(str, str + length);
puts(str);
while (next_permutation(str, str + length))
{
puts(str);
}
return 0;
}
用递归方法实现可参考下边这篇文章
http://blog.csdn.net/morewindows/article/details/7370155
- 全排列算法的实现
- 全排列算法的实现
- 全排列算法实现
- 简单的全排列算法实现
- 全排列和组合的实现算法
- 全排列的算法思想和实现
- C语言实现的全排列算法
- 全排列和组合的实现算法
- 递归实现的全排列算法
- 全排列算法的非递归实现
- 全排列递归算法的实现
- 使用递归实现全排列的算法
- 全排列的算法及c++实现
- C语言实现的全排列算法
- 数组全排列算法的python实现
- 全排列算法的递归实现
- Java实现的字符串全排列算法
- 全排列的递归实现算法
- [ImageMagick 学习] Fred's ImageMagick Scripts 转 C++ 的统一解决方案
- Qt之实现360安全卫士主界面(四)
- TreeView绑定算法的实现(无根节点)
- 各种算法的复杂度
- const int &i=10
- 全排列算法的实现
- Vim剪切板简介
- 学术分享搜索平台——中期报告
- 黑马程序员-初步面向对象
- Java中常用设计模式总结(转贴)
- jquery 获得选中的radio的值
- 2013阿里巴巴校园招聘笔试(大题,无解答)
- 链表合并算法
- Matlab中fft与fftshift命令的小结与分析