題目:輸入一個字串,輸出該字串中字元的所有組合。舉個例子,如果輸入abc,它的組合有a、b、c、ab、ac、bc、abc。
分析:在本系列部落格的第28題《字串的排列》中,我們詳細討論了如何用遞迴的思路求字串的排列。同樣,本題也可以用遞迴的思路來求字串的組合。
假設我們想在長度為n的字串中求m個字元的組合。我們先從頭掃描字串的第一個字元。針對第一個字元,我們有兩種選擇:一是把這個字元放到組合中去,接下來我們需要在剩下的n-1個字元中選取m-1個字元;而是不把這個字元放到組合中去,接下來我們需要在剩下的n-1個字元中選擇m個字元。這兩種選擇都很容易用遞迴實現。下面是這種思路的參考代碼:
void Combination(char* string){ if(string == NULL) return; int length = strlen(string); vector<char> result; for(int i = 1; i <= length; ++ i) { Combination(string, i, result); }} void Combination(char* string, int number, vector<char>& result){ if(number == 0) { vector<char>::iterator iter = result.begin(); for(; iter < result.end(); ++ iter) printf("%c", *iter); printf("\n"); return; } if(*string == '\0') return; result.push_back(*string); Combination(string + 1, number - 1, result); result.pop_back(); Combination(string + 1, number, result);}
由於組合可以是1個字元的組合,2個字元的字元……一直到n個字元的組合,因此在函數void Combination(char* string),我們需要一個for迴圈。另外,我們一個vector來存放選擇放進組合裡的字元。
博主何海濤對本部落格文章享有著作權。網路轉載請註明出處http://zhedahht.blog.163.com/。整理出版物請和作者聯絡。對解題思路有任何建議,歡迎在評論中告知,或者加我微博http://weibo.com/zhedahht或者http://t.163.com/zhedahht與我討論。謝謝。