算法练习-字符串全排列

练习问题来源

https://wizardforcel.gitbooks.io/the-art-of-programming-by-july/content/01.06.html

要求

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

例如输入字符串abc,则输出由字符a、b、c 所能排列出来的所有字符串:
abc、acb、bac、bca、cab 和 cba。

解法

输出全排列一般采用递归的方式,对集合中的元素依次选择一个作为首个元素,全排列其他的元素,在固定首个元素后的下一轮全排列中继续选择一个元素作为首个元素,以此方式递归地实现排列直至到两个元素的全排列,就成了两元素交换。

例如对 abcd 全排列,依次将 a, b, c, d 作为固定的首个元素,再排列剩下三个元素的全排列 a-bcd b-acd c-bad d-bca

// -----------------------------------------------------------------------
// Output full permutation.
// Referred to: http://blog.csdn.net/prstaxy/article/details/
// Use recursive algorithm to achieve this requirement.
// 2016/5/26

void SwapStr(char cStr[], int m, int n){
	char cTemp = cStr[m];
	cStr[m] = cStr[n];
	cStr[n] = cTemp;
}
void Permutation(char cStr[], int m, int n){
	if(m ==n)
	{
		for(int i=0; i<=n; i++)
			cout << cStr[i] << " ";
		cout <<endl;
	}
	else
	{
		for(int i=m; i<=n; i++)
		{
			SwapStr(cStr, i, m);
			Permutation(cStr, m+1, n);
			SwapStr(cStr, i, m);
		}
	}
}
int OutPermu1()  
{  
	char a[]= "1234";// {'1', '2', '3', '4', '5', '6', '7', '8'};  
	Permutation(a,0,3);
	return 0;  
}
// Use STL's function: next_permutation().
int OutPermu2()  
{  
	int a[] = {1,2,3};

	do  
	{  
		cout << a[0] << " " << a[1] << " " << a[2] << endl;  
	}  
	while (next_permutation(a,a+3));//求下一个排列数 #include<algorithm>  
	//while (prev_permutation(a,a+3));//求上一个排列数,初始数组用逆序来调用可以输出全排列  
	return 0;
}

void main()
{
    OutPermu1();
}
原文地址:https://www.cnblogs.com/nobodyzhou/p/5530686.html