全排列

本文介绍了一个简单的排列算法实现,通过递归的方式生成字符串的所有可能排列。文章详细解释了类`Permutation`的构造与析构过程,并展示了如何使用`printPermutation`方法来打印所有可能的字符排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Permutation
{

public :
	Permutation(const char* sour);
	~Permutation();

	void printPermutation(int start,int end);

private :
		char * p_str;
		void Swap(char &a,char &b);
};

#include "alla.h"
#include<string>
#include<iostream>

using namespace std;

Permutation::Permutation(const char *sour)
{
	if(sour == NULL)
	{
		p_str = NULL;
	}
	cout<<"Permutation"<<endl;
	int len = strlen(sour);
	p_str = new char[len + 1];
	int i = 0;
	cout<<len<<endl;
	while( sour[i] != '\0')
		{
			p_str[i] = sour[i];
			i++;
		}
	p_str[i] = '\0';
	
}

Permutation::~Permutation()
{
	if(p_str!=NULL)
		delete [] p_str;
	p_str = NULL;
	cout<<"~~~~permutation"<<endl;
	getchar();
}

void Permutation::printPermutation(int start,int end)
{
	if(start == end-1)
	{
		for(int i = 0; i < end; i++)
			cout<<p_str[i];
		cout<<endl;
	}
	else
	{
		for(int i = start; i < end; i++)
		{
	
		Swap(p_str[i],p_str[start]);
		printPermutation(start+1,end);//这里一定要是start +1 不 是i +1
		Swap(p_str[i],p_str[start]);
	
		}


	}
}

void Permutation::Swap(char &a,char &b)
{
	char c = a;
	a = b;
	b = c;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值