基于visual Studio2013解决面试题之0506取和为m的可能组合




题目



解决代码及点评

/*
    输入两个整数  n  和  m,从数列 1,2,3.......n  中  随意取几个数,
    使其和等于  m ,要求将其中所有的可能组合列出来.
*/

#include <iostream>
#include <string>
#include <list>
using namespace std;

// 通过递归查找和
void findSum(int m, int n, list<int> arr1)
{
	// 如果n太小,小到连所有加起来都比m小,那就结束了
	if (n*(n + 1) / 2 < m)
		return;

	// 使用另外一个链表arr2,避免arr1被污染
	list<int> arr2 = arr1;

	// 如果n比m小
	if (n <= m)
	{
		// 计算求和还差多少
		int remain = m - n;
		// 把n丢入到链表
		arr2.push_back(n);

		// 如果求和还差一些那么,要递归计算,剩下的差值,有多少方案实现
		if (remain > 0)
		{
			/* 带n的,和为m的数列 */
			findSum(remain, n - 1, arr2);
		}
		else  // 如果正好相等,那么就是找到了一种情况
		{
			// 打印结果
			list<int>::iterator it;
			for (it = arr2.begin(); it != arr2.end(); it++)
			{
				cout << *it << " ";
			}
			cout << endl;
		}
	}
	
	// 带n的组合完毕之后,求不带n的组合
	findSum(m, n - 1, arr1);
}


// 测试主函数
int main()
{
	int n = 6;
	int m = 10;
	list<int> arr;

	cout << "input n:";
	cin >> n;
	cout << "input m:";
	cin >> m;

	findSum(m, n, arr);

	system("pause");
	
	return 0;
}


代码下载及其运行

代码下载地址:http://download.csdn.net/detail/yincheng01/6704519

解压密码:c.itcast.cn


下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:

1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”


2)在下拉框中选择相应项目,项目名和博客编号一致

3)点击“本地Windows调试器”运行


程序运行结果









posted on 2013-12-16 22:07  三少爷的剑123  阅读(100)  评论(0编辑  收藏  举报

导航