字符串的组合

引用剑指offer

 1 //组合,从字符串str中取m个字符的所有组合,结果保存在vector中
 2 void combination(char* str,int m,vector<char>& result){
 3     //有两个停止条件:m==0或者*str=='\0'
 4     //先判断m
 5     if(m==0){
 6         for(vector<char>::iterator it=result.begin();it!=result.end();it++)
 7             cout<<*it;
 8         cout<<endl;
 9         return;
10     }
11     if(str==NULL|| *str=='\0')
12         return;
13     //情况1:当前字符被选中,m--
14     result.push_back(*str);
15     combination(str+1,m-1,result);
16     //上一步将含有*str的组合都输出了,下一步将*str移出result
17     result.pop_back();
18     //情况2:当前字符没被选中,m不变
19     combination(str+1,m,result);
20 }

 

posted @ 2014-09-20 11:26  liuzhiminxd  阅读(155)  评论(0编辑  收藏  举报