[Description]
Enter a string to print all characters in the string.
For example, if the input string ABC is used, all strings that can be sorted by characters A, B, and C are output.
ABC, ACB, Bac, BCA, cab, and CBA.
[Analysis]
Select each element from the set, and use it as the first element in the arrangement. Then, the remaining elements are arranged in full order. In this way, all elements are arranged recursively. Taking ABC as an example, we can do this: Take ABC as an example.
- Fix a and find the following BC: ABC, ACB. After the request is completed, a and B exchange to obtain the BAC.
- Fix B and locate the following AC: BAC and BCA. After the request is completed, place C in the first position to obtain the CBA.
- Fix C and find the order of the following BA: CBA and cab.
[Code]
<pre name="code" class="cpp">#include <stdio.h>#include <stdlib.h>#include <string.h>void swap(char *str, int begin, int k){char tmp;tmp = *(str + begin);*(str + begin) = *(str + k);*(str + k) = tmp;}int is_swap(char *str, int begin, int k){int i;for (i = begin; i < k; i ++)if(*(str + i) == *(str + k))return 0;return 1;}void permutation(char *str, int begin, int end){int k;if (begin == (end - 1)) {printf("%s\n", str);return;}for (k = begin; k < end; k++)if(is_swap(str, begin, k)) {swap(str, begin, k);permutation(str, begin + 1, end);swap(str, begin, k);}}int main(void){char str[10];int length;gets(str);length = strlen(str);printf("%d\n", length);permutation(str, 0, length);return 0;}