程序员面试题精选100题(59)-字符串的组合

来源:互联网 发布:mac图片翻页 编辑:程序博客网 时间:2024/04/30 04:00
// 程序员面试题精选100题(59)-字符串的组合.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <vector>#include <vector>using namespace std;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);}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* str,int i,int m,int n,vector<char>& vec)//choose m elements from n elements.i represent the position of the current handle. put elements into the vector until the size of the vector is n, then pop{//here is very important, in the recursive function. remember the search in the Binary tree, in the recursive search function there is an situation when the root is null, if (m==0)//just like this, we must consider that and handle it in the function as a special instance. otherwise the function maybe seem illogical. here, m==0 is an totally different situation, which marks the ending of a successful search, so we deal with it especially {for (int k=0;k<vec.size();k++){cout<<vec[k]<<" ";// why not queue or stack?  otherwise here will be wrong because they can not be accessed }cout<<endl;//every output is an answerreturn;}if(i<n)// n serve as the ending mark for the recursive function{vec.push_back(str[i]);// here also is critical, and it's difficult to make it clear in words, so ... think, practice, and think again//maybe we can think like this in according to the definition of the combination,choose one by one, until m then output.combination(str,i+1,m-1,n,vec);//suppose choose current element, need to choose another from the later elementvec.pop_back();// why pop? because it is recurse we must save and recover the scene. combination(str,i+1,m,n,vec);//for current result there are two ways related to the future results, on which we based to recurse. }}int _tmain(int argc, _TCHAR* argv[]){char *str="abcde";vector<char> vec;for (int m=1;m<=strlen(str);m++){combination(str,0,m,strlen(str),vec);//cout<<" ok "<<endl;}cout<<"as comparation"<<endl;Combination(str);system("pause");return 0;}

原创粉丝点击