perm.cpp

来自「常用算法与数据结构原代码」· C++ 代码 · 共 45 行

CPP
45
字号
// output all permutations of n elements

#include <iostream.h>

template<class T>
inline void Swap(T& a, T& b)
{	
	// Swap a and b.
	T temp = a; 
	a = b; 
	b = temp;
}

template<class T>
void Perm(T list[], int k, int m)
{
	// Generate all permutations of list[k:m].
	int i;
	if (k == m) 
	{
		// list[k:m] has one permutation, output it
		for (i=0; i<=m; i++)
			cout << list[i];
		cout << endl;
	}
	else
	{
		// list[k:m] has more than one permutation generate these recursively 
		for (i=k; i<=m; i++) 
		{
            Swap(list[k], list[i]);
            Perm(list, k+1, m);
            Swap(list[k], list[i]);
		}
	}
}

void main(void)
{
	char a[] = {'1', '2', '3'};
	int n = 3;
	cout << "The permutations of 123 are" << endl;
	Perm(a, 0, n-1);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?