字符串数组的全排列——数组
2015-06-30 09:32
447 查看
题目描述:
输入一个字符串,打印出该字符串中字符的所有排列。解题思路:
参考july大神的编程艺术系列.使用字典排序,求当前排列的下一个字典序列,即全排列的下一个排列.所谓字典序列,即给定两个偏序集A和B,(a,b)和(a′,b′)属于笛卡尔集 A × B,则字典序定义为
(a,b) ≤ (a′,b′) 当且仅当 a < a′ 或 (a = a′ 且 b ≤ b′)。
所以给定两个字符串,逐个字符比较,那么先出现较小字符的那个串字典顺序小,如果字符一直相等,较短的串字典顺序小。
例如:abc < abcd < abde < afab。
起点: 字典序最小的排列, 1-n , 例如12345
终点: 字典序最大的排列,n-1, 例如54321
过程: 从当前排列生成字典序刚好比它大的下一个排列
next_permutation算法
定义
升序:相邻两个位置ai < ai+1,ai 称作该升序的首位
步骤(二找、一交换、一翻转)
找到排列中最后(最右)一个升序的首位位置i,x = ai
找到排列中第i位右边最后一个比ai 大的位置j,y = aj
交换x,y
把第(i+ 1)位到最后的部分翻转
拿21543举例,那么,应用next_permutation算法的过程如下:
x = 1;
y = 3
1和3交换
得23541
翻转541
得23145
参考代码:
<span style="font-size:18px;">class Solution{ public: void calcAllpermutaion(char *perm, int from, int to) { if (to <= 1) return; if (from == to) { for (int i = 0; i <= to; i++) cout << perm[i]; cout << endl; } else { for (int j = from; j <= to; j++) { swap(perm[j], perm[from]); calcAllpermutaion(perm, from + 1, to); swap(perm[j], perm[from]); } } } bool calcNextPermutation(char *perm, int len){ int i = 0, j = 0; for (i = len - 2; (i >= 0) && (perm[i] >= perm[i + 1]); i--); if (i < 0) return false; for (j = len - 1; (j>i) && (perm[j] <= perm[i]); j--); swap(perm[i], perm[j]); reverse(perm + i + 1, perm + len - 1); return true; } };</span>
参考:http://taop.marchtea.com/01.06.html
相关文章推荐
- Android中的APK,TASK,PROCESS,USERID之间的关系
- VC++ 文件操作
- 微信浏览器自带的返回上一页的停留位置 scrollTop
- Machine Learning---LMS 算法数学说明
- Good habits about programming
- 无线传感网络基础
- 使用SpannableString 修饰TextView的样式
- 不要一个人吃饭
- 程序员为什么千万不要重写代码?
- MAC 使用
- qt QComboBox dataChanged()信号的发射
- c# 引用类型与值类型的区别详解(转)
- Apache Shiro 使用手册(一)Shiro架构介绍
- JSON
- Machine Learning---LMS 算法
- MongoDB怎样插入数据
- Creational模式之Prototype模式
- linux signal 列表
- 【JAVA】LinkedList使用详解
- HBase查询引擎—Phoenix