您的位置:首页 > 职场人生

剑指Offer----面试题28----扩展:从1到n中随意取若干数使之与某一数相等

2016-06-06 23:52 387 查看

题目

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

源代码:
#include <iostream>
#include <list>
using namespace std;
list<int> list1;
void find_factor(int sum, int n)
{
//递归出口
if (n <= 0 || sum <= 0)
return;
//输出找到的数
if (sum == n)
{
list1.reverse();
for (list<int>::iterator iter = list1.begin(); iter != list1.end(); iter++)
cout << *iter << "+";
cout << n << endl;
list1.reverse();
}
list1.push_front(n);
find_factor(sum - n, n - 1);//n放在里面
list1.pop_front();
find_factor(sum, n - 1);//n不放在里面
}

int main(void)
{
int sum, n;
cin >> sum >> n;
cout << "所有可能的序列,如下:" << endl;
find_factor(sum, n);

system("pause");
return 0;
}


运行结果:
10
9
所有可能的序列,如下:
9+1
8+2
7+3
7+2+1
6+4
6+3+1
5+4+1
5+3+2
4+3+2+1
请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息