第二十一题(求数组中和为特定数的所有组合)

本文介绍了一种使用递归方法解决从给定数列中选取若干个数使其和等于目标值的问题,并通过链表记录参与求和的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第21 题

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


采用递归的方式实现

每个数字参与求和或者不参与,通过链表record记录参与求和的数字

终止条件为index>n,此时说明求和失败

当index<=n且index==m时,说明找到一个满足条件的组合,打印之,同时继续寻找该index不参与求和时的组合

当index<=n且index<m时,同样分是否参与求和两种情况处理。

算法复杂度为O(2^n)

代码:

#include<iostream>
using namespace std;
#include<list>
namespace MS100P_21
{
	//递归
	void helper(int index, int m, int n, list<int>& record)
	{
		if (index <= n)
		{
			if (index == m)
			{
				helper(index + 1, m, n, record);	
				record.push_back(index);
				for (list<int>::iterator iter = record.begin(); iter != record.end(); iter++)
					cout << *iter << ' ';
				cout << endl;
				record.pop_back();
			}
			if (index < n)
			{
				helper(index + 1, m, n, record);
				record.push_back(index);
				helper(index + 1, m - index, n, record);
				record.pop_back();
			}

		}
	}
	void findCombination(int m, int n)
	{
		list<int> record;
		helper(0, m, n, record);
	}

	void test()
	{
		findCombination(10, 20);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	MS100P_21::test();
	return 0;
}

运算结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值