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

// 程序员面试题精选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 answer
		return;
	}
	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 element
		vec.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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值