N的加法组合问题

网上的解法很多,我自己昨晚也想了两个多小时,今天上班途中偶尔突发灵感,中午吃饭的时候写了一下


// n的加法组合.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 

using namespace std;


#define MIN(A, B) A>B?B:A

void print_list(std::list::iterator &itr1, std::list::iterator &itr2)
{
	std::list::iterator itr = itr1;

	while (itr != itr2)
	{
		printf("%d+", (*itr));
		++itr;
	}
}

void fooImpl(int N, int remain, std::list &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 mList;

	for (int curN = N; curN >= 1; curN--)
	{
		fooImpl(curN, N-curN, mList);
	}
}


int main( void ) 
{
	foo(6);
	return 0;
}


输出结果



你可能感兴趣的:(C++/C,算法)