Programming method study notes - 1.3 full arrangement of strings

Topic description:

Enter a string and print out all permutations of the characters in the string. For example, the input string "abc" will output all the strings "abc", "acb", "bac", "bca", "cab that can be arranged by the characters 'a', 'b', 'c' ", "cba".

Recursive method:

In the case of the string "a" (N=1), the required operation is direct output.

In the case of the string "ab" (N=2), you can use 'a' as the first position to arrange "b"; you can also use 'b' as the first position to arrange "a".

In the case of the string "abc" (N=3), you can use 'a' as the first position to arrange "bc"; you can also use 'b' as the first position to arrange "ac"; you can also use 'c' As the first place, "ab" is arranged.

The above steps can be abstracted as:

1) Swap the from-th bit with the from+i-th bit in the string.

2) Fully sort the form+1 bit to the end.

3) Swap the from-th bit with the from+i-th bit in the string, and restore the string for the next exchange.

The time complexity of this algorithm is O(n!) and the space complexity is O(1).

void arrange(char * str, int from, int to)
{
	if (from == to)
		cout << str << endl;
	else
	{
		for (int i = 0; i <= (to - from); i++)
		{
			swap(str[from], str[from + i]);
			arrange(str, from + 1, to);
			swap(str[from], str[from + i]);
		}
	}
}

lexicographical order:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325162778&siteId=291194637