列出某數所有的加法式

  1. // ***************************************************************
  2. //  Addition   version:  1.0   ·  date: 12/30/2008
  3. //  -------------------------------------------------------------
  4. //  Author: ZhangLiang
  5. //  -------------------------------------------------------------
  6. //  Copyright (C) 2008 - All Rights Reserved
  7. // ***************************************************************
  8. // 
  9. // ***************************************************************
  10. #include "stdafx.h"
  11. //////////////////////////////////////////////////////////////////////////
  12. //Get the min value
  13. inline int MinValue( int val1,int val2)
  14. {
  15.     return val1<val2? val1:val2;
  16. }
  17. //////////////////////////////////////////////////////////////////////////
  18. //Output a result
  19. int OutPut(list<int>& addition)
  20. {
  21.     for (list<int>::iterator it = addition.begin();it!=addition.end();it++)
  22.     {
  23.         cout<<*it<<" ";
  24.     }
  25.     cout<<"/n";
  26.     return 0;
  27. }
  28. //////////////////////////////////////////////////////////////////////////
  29. //list all result
  30. //sum: the operate value
  31. //addition: the container of addend
  32. //maxAddend: the max addend
  33. int Addition(int sum,list<int>& addition,int maxAddend)
  34. {      
  35.     if (0== sum)
  36.     {
  37.         OutPut(addition);
  38.         return 0;
  39.     }
  40.     for (int i = 1; i<=maxAddend;i++)
  41.     {
  42.         addition.push_back(i);
  43.         Addition(sum-i,addition,MinValue(sum-i,i));
  44.         addition.pop_back();
  45.     }
  46.     return 0;
  47. }
  48. //////////////////////////////////////////////////////////////////////////
  49. //main function
  50. int _tmain(int argc, _TCHAR* argv[])
  51. {
  52.     list<int> lstAddition;//the container of addend
  53.     int nSum = 10; // the operate value
  54.     Addition(nSum,lstAddition,nSum-1);
  55.     system("pause");
  56.     return 0;
  57. }

Addition函數是實現主要的功能函數,代碼就幾行而已,很簡單。只是用到了遞歸。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章