[Algorithm diary] Recursive realization of the full arrangement problem

Full arrangement definition : Take m (m≤n) elements from n different elements and arrange them in a certain order, which is called an arrangement in which m elements are taken from n different elements. When m=n, all permutations are called full permutations.

Formula: the total number of permutations f(n)=n! (definition 0!=1)
such as 123 permutation: 123 213 132 231 321 312
algorithm idea : n numbers, first determine the first digit, and then in each case The following n-1 numbers continue to be arranged in full, and to continue the full arrangement is to determine the first place first, and then the remaining parts continue to be arranged in full, so that the remaining part will eventually be reduced, reducing to only one element and output, at this time All arranged successfully.

as the picture shows
Insert picture description here

The core algorithm is as follows```

void Perm(T list[], int k, int m)// 产生list[k:m]的所有排列
{
	if (k == m) {// 只剩下一个元素
		for (int i = 0; i <= m; i++) {
			cout << list[i];
		}
		cout << endl;
		
	}
	for (int i = k; i <= m; i++) {
		Swap(list[k], list[i]);
		Perm(list, k + 1, m);
		Swap(list[k], list[i]);//为了还原,避免重复。即保证此时循环数后面的数是初始顺序。
	}
}

The test code is as follows:


#include <iostream>
#include <cassert>
using namespace std;
#define length 3

template<typename T>
inline void Swap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}

template<typename T>
void Perm(T list[], int k, int m)// 产生list[k:m]的所有排列
{
	if (k == m) {// 只剩下一个元素
		for (int i = 0; i <= m; i++) {
			cout << list[i];
		}
		cout << endl;
		
	}
	for (int i = k; i <= m; i++) {
		Swap(list[k], list[i]);
		Perm(list, k + 1, m);
		Swap(list[k], list[i]);
	}
}
int main()
{
	char list[length] = { 'a','b','c' }; 
	Perm(list, 0, length - 1);
	
}

Guess you like

Origin blog.csdn.net/wdxyxshark/article/details/108711856