- // ***************************************************************
- // Addition version: 1.0 · date: 12/30/2008
- // -------------------------------------------------------------
- // Author: ZhangLiang
- // -------------------------------------------------------------
- // Copyright (C) 2008 - All Rights Reserved
- // ***************************************************************
- //
- // ***************************************************************
- #include "stdafx.h"
- //////////////////////////////////////////////////////////////////////////
- //Get the min value
- inline int MinValue( int val1,int val2)
- {
- return val1<val2? val1:val2;
- }
- //////////////////////////////////////////////////////////////////////////
- //Output a result
- int OutPut(list<int>& addition)
- {
- for (list<int>::iterator it = addition.begin();it!=addition.end();it++)
- {
- cout<<*it<<" ";
- }
- cout<<"/n";
- return 0;
- }
- //////////////////////////////////////////////////////////////////////////
- //list all result
- //sum: the operate value
- //addition: the container of addend
- //maxAddend: the max addend
- int Addition(int sum,list<int>& addition,int maxAddend)
- {
- if (0== sum)
- {
- OutPut(addition);
- return 0;
- }
- for (int i = 1; i<=maxAddend;i++)
- {
- addition.push_back(i);
- Addition(sum-i,addition,MinValue(sum-i,i));
- addition.pop_back();
- }
- return 0;
- }
- //////////////////////////////////////////////////////////////////////////
- //main function
- int _tmain(int argc, _TCHAR* argv[])
- {
- list<int> lstAddition;//the container of addend
- int nSum = 10; // the operate value
- Addition(nSum,lstAddition,nSum-1);
- system("pause");
- return 0;
- }
Addition函數是實現主要的功能函數,代碼就幾行而已,很簡單。只是用到了遞歸。