zoukankan      html  css  js  c++  java
  • 字符串数组的全排列——数组

    题目描写叙述:

    输入一个字符串,打印出该字符串中字符的全部排列。


    解题思路:

    參考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 称作该升序的首位
    步骤(二找、一交换、一翻转)

    1. 找到排列中最后(最右)一个升序的首位位置i,x = ai
    2. 找到排列中第i位右边最后一个比ai 大的位置j。y = aj
    3. 交换x,y
    4. 把第(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>




  • 相关阅读:
    RabbitMQ:六、网络分区
    RabbitMQ:五、高阶
    RabbitMQ:四、跨越集群
    数据结构:红黑树
    RabbitMQ:三、进阶
    面对对象多态的异常
    面向对象三大特征---多态
    面对对象继承的优点和缺点
    面对对象当中的代码块
    面对对象this关键字
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6938246.html
Copyright © 2011-2022 走看看