每天學習一算法系列(21)(輸入兩個整數n 和m,從數列1,..n 中隨意取幾個數使和等於m)

 

題目:

編程求解:
輸入兩個整數n 和m,從數列1,2,3.......n 中隨意取幾個數,使其和等於m ,要求將其中所有的可能組合列出來.

 

思路一:

這是比較典型的揹包問題,可以用貪心算法來解。

分析:記整數p可以用1,2,3...q的所有不重複數之和表示的組合爲C(p,q),則C(p,q)可以表示爲以下的組合:
{q} + C(p-q,q-1)  (如果q<=m)
或者
C(p,q-1)
即要麼包含q,要麼不包含q。

 

代碼如下:

/*=============================
Coypright by yuucyf. 2011.08.06
==============================*/

#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;

void FindCombination(int nSum, int nValue)
{
	static list<int> listComb;
	if(nValue < 0 || nSum < 0)
		return;

	if (nSum >  0)
	{
		listComb.push_front(nValue);
		FindCombination(nSum-nValue, nValue-1);

		listComb.pop_front();
		FindCombination(nSum, nValue-1);
	}
	else
	{
		cout << "組合:";
		for(list<int>::iterator it = listComb.begin(); it != listComb.end(); ++it)
			cout << " " << *it;
		cout << endl;
	}

	
}

int _tmain(int argc, _TCHAR* argv[])
{
	int m, n;
	cout<<"請輸入你要等於多少的數值m:"<< endl;
	cin >> m;
	cout<<"請輸入你要從1.....n 數列中取值的n:"<< endl;
	cin >> n;
	cout << "======================" << endl;

	FindCombination(m, n);

	return 0;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章