递归实例——C语言实现全排列

  最近在学习数据结构,感觉递归算法很有意思,写了一个用递归实现的全排列实例,如有错误欢迎批评指正!


#include "stdafx.h"
void permutation(char s[], int b, int e) //被排列的数组中不能有重复的元素
{
	if(0<=b && b<=e)
	{
		if(b==e)
		{
			printf("%s\n",s);
		}
		else
		{
			int i = 0;
			for(i=b; i<=e; i++)
			{
				char c = s[b];
				s[b] = s[i];
				s[i] = c;

				permutation(s, b+1, e);

				c = s[b];
				s[b] = s[i];
				s[i] = c;
			}
		}
	}
}

void permutation_2(char s[], int b, int e) //被排列的数组中可以有重复的元素
{
	static int count = 0;
	char repeat[sizeof(s)/sizeof(char)] = {NULL}; //用于存储重复的元素
	if(0<=b && b<=e)
	{
		if(b==e)
		{
			count++;
			printf("%d: %s\n",count,s);
		}
		else
		{
			int i = 0;
			int j = 0;
			int t = 0; //记录重复元素的个数
			int repeat_num = 0; //记录连续重复元素的个数
			int flag = 0;
			for(i=b; i<=e; i++)
			{
				for(j = 0;j<t;j++)
				{
					if(s[i]==repeat[j])
					{
						flag = 1;
						repeat_num++;
						break;	
					}
				}
				if(flag == 1)
				{
					continue;
				}
				else
				{
					repeat[t] = s[i];
					t++;
					char c = s[b];
					s[b] = s[i];
					s[i] = c;

					permutation_2(s, b+1+repeat_num, e);

					c = s[b];
					s[b] = s[i];
					s[i] = c;
				}
			}
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	char s[] = "abbcccc";
	permutation_2(s,0,6);
	return 0;
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值