字符串组合递归求解

一 问题描述:

输入字符串,如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();
}


 

三 测试

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值