一 问题描述:
输入字符串,如abcde,求它的3的组合
二:代码
/*
This is a free Program, You can modify or redistribute it under the terms of GNU
*Description:字符串组合递归求解
*Language: C++
*Development Environment: VC6.0
*Author: Wangzhicheng
*E-mail: 2363702560@qq.com
*Date: 2012/12/14
*/
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
/*
*Solution类封装了使用了递归的组合算法
*str:指向当前用户输入的字符串
*tmp:指向组合的字符串
*selectM:选取几个数来组合
*/
class Solution {
private:
char *str;
char *tmp;
int selectM;
/*
*递归实现组合
*selectStart:指向str中当前被操作的字符
*selectCur:指向tmp中当前被操作的字符
*/
void Combine(int selectStart,int selectCur) {
static int cnt;
if(selectCur>=selectM) { //一种新的组合产生
cout<<"第"<<++cnt<<"种组合是:"<<tmp<<endl;
}
else {
int i;
for(i=selectStart;str[i];i++) {
tmp[selectCur]=str[i];
Combine(i+1,selectCur+1);
}
}
}
public:
Solution(const char *string,int selectM) {
int n=strlen(string);
str=new char[n+1];
if(!str) exit(1);
strncpy(str,string,n+1);
this->selectM=selectM;
tmp=new char[selectM+1];
if(!tmp) exit(1);
tmp[selectM+1]='\0';
}
void Combine() {
Combine(0,0);
}
};
void main() {
Solution s("abcdef",2);
s.Combine();
}
三 测试