Fortune left full array based method class8- title print string 4

1. Title: Printing all permutations of a string

2. Analysis

The first element of the first fixed character string, and then solving the whole arrangement of the remaining strings, and another method for solving this same problem, recursively solving
① through all possible first characters: use of exchange, the exchange of other elements according to the order a first element
② fixed first element, then the element from the second recursive
③ recursive termination condition is the current element is the last element: index string length minus one

3. The complete code

#include<iostream>
#include<string>
using namespace std;

void swap(char &a,char &b)
{
	char tmp = a;
	a = b;
	b = tmp;
}
void print(string s,int beg)
{ 
	if(beg == s.size() - 1)
	{
		cout << s << endl;
		return ;
	}
	else
	{
		for(int i = beg; i < s.size();i++)
		{
			swap(s[i],s[beg]);	//交换
			print(s,beg + 1);	//递归
			swap(s[i],s[beg]);	//回溯,交换回来
		}
	}
}

int main()
{
	string s = "abc";
	print(s,0);

	return 0;
}

4. Results and additional requirements

Here Insert Picture Description
Notes:
1. This problem did not request to heavy, if desired deduplication may
① the character strings to be output is added to set the container, find no longer output
② using vector for all of the string is stored, to find the find function, no further output
2. the required output in lexicographic order, main () function to sort strings using the sort function, and then continue to

Published 51 original articles · won praise 1 · views 1362

Guess you like

Origin blog.csdn.net/shi_xiao_xuan/article/details/104826037