数据结构与算法分析——c++语言描述

数据结构与算法分析——c++语言描述

编写带有下列声明的两个例程:
void permute(String str);
void permute(char[] str, int low, int high);
第一个例程是个驱动程序,它调用第二个例程并显示String str中字符的所有排列。
例如,str是"abc", 那么输出的串则是abc,acb,bac,bca,cab,cba,第二个例程使用递归。

#include<iostream>
#include<string>
using namespace std;
void permute(string &str);
void permute(string &str,int low,int high);
void swap(string &str,int a,int b);
bool isswap(string &str,int a,int b);

int main()
{
	string str="abc";
	permute(str);
}
void swap(string &str,int a,int b)
{
	if(str[a]==str[b])
	return ;
	char c=str[a];
	str[a]=str[b];
	str[b]=c;
}
void permute(string &str)
{
	permute(str,0,str.length());
}
void permute(string &str,int low,int high)
{
	if(high-low==1)
	{
		string s;
		for(int i=0;i<high;i++)
		{
			s+=str[i];	
		}
		cout<<s<<endl;
	}
	for(int i=low;i<high;i++)
	{
		swap(str,low,i);
		permute(str,low+1,high);
		swap(str,low,i);
	}
}

书上两个例程中str前用了const,我自己写的时候发现如果加了const那么swap函数的调用就会出现错误。所以我就把const删除了。
从别的地方看到有重复的可能

去重+输入

#include<iostream>
#include<string>
using namespace std;
void permute(string &str);
void permute(string &str,int low,int high);
void swap(string &str,int a,int b);
bool isswap(string &str,int a,int b);

int main()
{
	string str;
	cin>>str;
	permute(str);
}
void swap(string &str,int a,int b)
{
	if(str[a]==str[b])
	return ;
	char c=str[a];
	str[a]=str[b];
	str[b]=c;
}
bool isswap(string &str,int a,int b)
{
	for(int i=a;i<b;i++)
		if(str[i]==str[b])
			return false;
		return true;
}
void permute(string &str)
{
	permute(str,0,str.length());
}
void permute(string &str,int low,int high)
{
	if(high-low==1)
	{
		string s;
		for(int i=0;i<high;i++)
		{
			s+=str[i];	
		}
		cout<<s<<endl;
	}
	for(int i=low;i<high;i++)
	{
		if(isswap(str,low,i)) 
		{
			swap(str,low,i);
			permute(str,low+1,high);
			swap(str,low,i);
		}
		
	}
}

请指教。

猜你喜欢

转载自blog.csdn.net/AQ_No_Happy/article/details/104126576