现在的位置: 首页 > 综合 > 正文

满足条件的两个数或多个数

2018年12月13日 ⁄ 综合 ⁄ 共 438字 ⁄ 字号 评论关闭

主要参考:http://blog.csdn.net/v_JULY_v/article/details/6419466

2010年中兴面试题
编程求解:
输入两个整数 n 和 m,从数列1,2,3.......n 中 随意取几个数,
使其和等于 m ,要求将其中所有的可能组合列出来。


对于每个数都要算下,放与不放的情况:


void Find(int t,int sum,list<int>& lst)
{
	if(sum ==0)
	{
		list<int>::iterator it;
		for(it = lst.begin();it!=lst.end();++it)
			cout<<*it<<" ";
		cout<<endl;
	}
	if(t>sum)
		return;
	if(t+1<=sum)
		Find(t+1,sum,lst);
	
	if(t<=sum)
	{
		lst.push_back(t);
		Find(t+1,sum - t,lst);
		lst.pop_back();
	}
	
}
int main()
{

	list<int> lst;
	Find(1,6,lst);

	return 0;
	
}
【上篇】
【下篇】

抱歉!评论已关闭.