Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

打印所有的组合(组合问题C++实现)

$
0
0

写一个程序,打印出以下的序列。
(a),(b),(c),(d),(e)........(z)
(a,b),(a,c),(a,d),(a,e)......(a,z),(b,c),(b,d).....(b,z),(c,d).....(y,z)
(a,b,c),(a,b,d)....(a,b,z),(a,c,d)....(x,y,z)
....
(a,b,c,d,.....x,y,z)

#include<iostream>
#include<vector>
#include<string>  
#include<iterator>  
using namespace std;
using std::iterator;
void CombineRescure(vector<char> &str,vector<char>::iterator pStr,vector<char> &result,int count);
void Combine(vector<char> str,int n)
{
	if(str.empty())
		return;
	vector<char> result;
	CombineRescure(str,str.begin(),result,n);
}
void CombineRescure(vector<char> &str,vector<char>::iterator pStr,vector<char> &result,int count)
{
	if(count==0)
	{
		cout<<"(";
		//copy(result.begin(),result.end(),ostream_iterator<char,char>(cout,","));
		for(int i=0;i<result.size();i++)
		{
			cout<<result[i];
			if(i!=result.size()-1)
				cout<<",";
		}
		cout<<"),";
		return;
	}
	if(pStr!=str.end())
	{
		result.push_back(*pStr);
		CombineRescure(str,pStr+1,result,count-1);
		result.erase(result.end()-1);
		CombineRescure(str,pStr+1,result,count);
	}
}
int main()
{
	vector<char> str;
	for(int i=0;i<4;i++)
	{
		str.push_back('a'+i);
	}

	for(int i=1;i<=str.size();i++)
	{
		Combine(str,i);
		cout<<endl;
	}
	return 0;
}
因为结果太多,所以只打印a~d的结果

作者:ywjun0919 发表于2013-9-5 22:44:25 原文链接
阅读:55 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>