題目: 輸入一個字符串, 打印出該字符串中字符的所有排列.
方法: 使用遞歸依次交換位置, 打印輸出.
代碼:
/* * main.cpp * * Created on: 2014.6.12 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #includevoid Permutation(char* pStr, char* pBegin); void Permutation(char* pStr) { if(pStr == NULL) return; Permutation(pStr, pStr); } void Permutation(char* pStr, char* pBegin) { if(*pBegin == '') { printf(%s , pStr); } else { for(char* pCh = pBegin; *pCh != ''; ++ pCh) { char temp = *pCh; *pCh = *pBegin; *pBegin = temp; Permutation(pStr, pBegin + 1); temp = *pCh; *pCh = *pBegin; *pBegin = temp; } } } void Test(char* pStr) { if(pStr == NULL) printf(Test for NULL begins: ); else printf(Test for %s begins: , pStr); Permutation(pStr); printf( ); } int main(void) { char str[] = abc; Test(str); return 0; }
Test for abc begins: abc acb bac bca cba cab