字符的排列

问题:输入一字符串(要求不存在重复字符),打印出该字符串中字符中字符的所有排列。

思路:求所有可能出现在第一个位置的字符,把第一个字符和其后面的字符一一交换。固定第一个字符,求后面所有字符的排列。这个时候扔把后面的所有字符分成两部分:后面字符的第一个字符,以及这个字符之后的所有字符,然后把第一个字符逐一和它后面的字符交换。

 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 }

posted on 2016-06-29 21:00  三颗心  阅读(410)  评论(0编辑  收藏  举报

导航