网上的解法很多,我自己昨晚也想了两个多小时,今天上班途中偶尔突发灵感,中午吃饭的时候写了一下
// n的加法组合.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;
#define MIN(A, B) A>B?B:A
void print_list(std::list<int>::iterator &itr1, std::list<int>::iterator &itr2)
{
std::list<int>::iterator itr = itr1;
while (itr != itr2)
{
printf("%d+", (*itr));
++itr;
}
}
void fooImpl(int N, int remain, std::list<int> &mList)
{
if (remain == 0)
{
print_list(mList.begin(),mList.end());
cout << N << endl;
return;
}
mList.push_back(N);
for (int loop = MIN(N, remain); loop >= 1; loop--)
{
fooImpl(loop, remain-loop, mList);
}
mList.pop_back();
}
void foo(int N)
{
std::list<int> mList;
for (int curN = N; curN >= 1; curN--)
{
fooImpl(curN, N-curN, mList);
}
}
int main( void )
{
foo(6);
return 0;
}
输出结果