字符串的组合

Q:输入一个字符串,输出该字符串中字符的所有组合。


A:假设一个字符串长度为n,要求长度为m的所有组合。我们考虑字符串中一个字符,我们有两种选择:将其加入组合或者不加入组合。当加入组合时,我们还需要从该字符后面的子串中选取m-1个字符;当不加入组合时,我们需要从该字符后面的子串中选取m个字符,所以递归+回溯即可解出。


#include <iostream>
#include <vector>
using namespace std;


void Combination(char* str,int m)
{
	static vector<char> Result;
	
	if(m==0)
	{
		for(vector<char>::iterator it=Result.begin();it!=Result.end();++it)
			cout <<*it;
		cout <<endl;
		return;
	}
	if(*str=='\0')
		return;
	
	Result.push_back(*str);
	Combination(str+1,m-1);
	Result.pop_back();
	Combination(str+1,m);
	
}

int main()
{
	char str[50];
	while(cin >>str)
	{
		int n=strlen(str);
		Combination(str,2);
	}
	return 0;
}
posted @ 2012-06-14 20:07  Cavia  阅读(453)  评论(0编辑  收藏  举报