首页 > 技术文章 > 寻找和为定值的多个数

wft1990 2017-06-21 16:45 原文

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

// 寻求和为定值的多个数.cpp : 定义控制台应用程序的入口点。

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

list<int> nums;
void func(int n, int m)
{
    if(n<=0 || m<=0)
        return;
    if(n == m)
    {
        for(list<int>::iterator iter = nums.begin();iter!=nums.end();iter++)
            cout<<*iter<<"+";
        cout<<n<<endl;
    }
    nums.push_front(n);
    func(n-1, m-n);
    nums.pop_front();
    func(n-1,m);

}

int main()
{
    func(10,12);
    return 0;
}

 

推荐阅读