Algorithm recursion-the problem of complete arrangement of sets

Set permutation problem

Suppose the set R = {r1, r2, r3… rn}, obviously the number of all permutations is n! .
So how do you display all the permutations of the collection?
It can be implemented in a recursive manner.

Problem-solving ideas
If the set has n elements, then it can be regarded as the n-1 elements are completely arranged and then the remaining element is added. Because it is a complete arrangement, each element will be left once. (For example:
R = full arrangement of {1,2,3}.
If 1 is left, then {2, 3} is arranged first, and then combined with 1, the result is 1 23, 1 32.
If 2 is left, then {1, 3} array, combined with 2, the result is 2 13, 2 31.
If 3, the result is 3 12, 321.)

Continue, the complete arrangement of n-1 numbers can be regarded as the complete arrangement of n-2 numbers, and then combined with the remaining number. This is repeated with the previous operation. Layer by layer simplifies down to the end. Only one element is left in the sequence, and the recursion ends.

Look at the specific implementation

//定义一个数组,表示集合
//参数k为起始排列数的下标,m为结束下标。
void Perm(int list[], int k, int m)	
{
	if(k==m) 			//递归结束标志,起始下标=结束下标,代表集合内就一个数了。
	{
		for(int i=0;i<=m;i++)		
			cout<<list[i]<<" ";	//此时数组内的元素已经被交换好位置,一种排列可以输出。
		cout<<endl;
	}
	else
	{
		for(int j=k;j<=m;j++)	 //变量 j从起始k开始,到m结束,表示被剩下的那个数,
			{
				swap(list[k],list[j]);//刚开始k=j,就相当于1=1;1被剩下,j++后,变成2,相当于2被剩下,2在数组中代替1的位置.
				Perm(list,k+1,m);  //除了被剩下的,其余元素排列,相当于 23排列,再继续递归
				swap(list[k],list[j]);	//输出一种正确排列后需要把下标再换回。不然就乱套了
			}
	}
		
}

Summary
This kind of problem-solving method is to change the position of the elements in the array through a recursive algorithm and then output.
Use recursion to decompose n elements step by step:
n becomes any remaining number (n cases) and n-1 numbers.

Until the last element remains as a sign of the end of recursion.
The alternation of positions in the array is also difficult. It is easy to understand directly from the above picture.
Insert picture description here
The case of the remaining 1 is the first column, and
the case of the remaining 2 is the second column
... You
will find that the difference between the first column and the second column is that 1 and 2 When the position of the column is different, when the arrangement of the second column is required, you only need to replace the position of 1 with 2 as well as the other columns.

Published 36 original articles · praised 3 · visits 3531

Guess you like

Origin blog.csdn.net/qq_43628835/article/details/105555138