Data structure and algorithm analysis-C++ language description

Data structure and algorithm analysis-C++ language description

Write two routines with the following declarations:
void permute(String str);
void permute(char[] str, int low, int high); The
first routine is a driver, it calls the second routine and Display all permutations of characters in String str.
For example, if str is "abc", the output string is abc, acb, bac, bca, cab, cba, and the second routine uses recursion.

#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);
	}
}

In the two routines in the book, const is used before str. When I wrote it myself, I found that if const was added, the swap function call would be wrong. So I deleted the const.
Seen from other places there is a possibility of duplication

Deduplication + input

#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);
		}
		
	}
}

Please advise.

Guess you like

Origin blog.csdn.net/AQ_No_Happy/article/details/104126576