思路:求所有可能出現在第一個位置的字符,把第一個字符和其後面的字符一一交換。固定第一個字符,求後面所有字符的排列。這個時候扔把後面的所有字符分成兩部分:後面字符的第一個字符,以及這個字符之後的所有字符,然後把第一個字符逐一和它後面的字符交換。
1 #include<stdio.h>
2 #include "stdafx.h"
3 #include<tchar.h>
4
5 void Permutation(char* pStr, char* pBegin);
6
7 void Permutation(char* pStr)
8 {
9 if(pStr == NULL)
10 return;
11
12 Permutation(pStr, pStr);
13 }
14
15 void Permutation(char* pStr, char* pBegin)
16 {
17 if(*pBegin == '\0')
18 {
19 printf("%s\n", pStr);
20 }
21 else
22 {
23 for(char* pCh = pBegin; *pCh != '\0' ; ++pCh)
24 {
25 char temp = *pCh;
26 *pCh = *pBegin;
27 *pBegin = temp;
28
29 Permutation(pStr, pBegin + 1);
30
31 temp = *pCh;
32 *pCh = *pBegin;
33 *pBegin = temp;
34 }
35 }
36 }
37
38 int main()
39 {
40
41 char string[] = "abc";
42 Permutation(string);
43
44 return 0;
45 }
