第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;
}
运算结果: