递归求解全排列

复习线代时想的=。=

递归最简单的理解就是不断的调用自己,形式(作图)上可以和树做类比

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
const int MAXN = 100;
int n;
bool visited[MAXN];
int print[MAXN];

void permulation(int num[], int len)
{
	if (len == 0)
	{
		for (int i = n; i >= 1; i--)
		{
			cout << print[i] << " ";
		}
		cout << endl;
		return;
	}
	for (int i = 1; i <= n; i++)
	{
		if (visited[i])
		{
			continue;
		}
		print[len] = num[i];
		visited[i] = true;
		permulation(num, len - 1);
		visited[i] = false;
	}
}
int main()
{
	int num[MAXN];
	memset(visited, false, sizeof(visited));
	cout << "输入全排序序列个数和值:" << endl;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> num[i];
	}
	permulation(num, n);
	return 0;
}


posted @ 2014-04-10 08:39  N3verL4nd  阅读(186)  评论(0编辑  收藏  举报