整数A有多少加法表达式

题目: 整数A=a1+a1+a3+…+an (0<a1<=a2<=a3<=…<=an),求集合G={g|g={a1,a2,a3,…,an}}

分析:

      1. 求A的表达式,假设已经确定an的值,那么接下来就是求解A-an的表达式。令B=A-an

      2. 求B的表达式,假定已经确定bn的值,那么接下来就是求解B-bn的表达式。令C=B-bn

      3. 求C的表达式,…

      由1-3步可以看出,这是一个递归的过程。那么先看一下,对于求A的表达式,an,bn,cn,…的值的取值范围:

      很显然 :1<=an<=A,那么:

                  1<=bn<=an,  1<=cn<=bn,…

代码:

  1: #include<iostream>

  2: #include<vector>

  3: #include<algorithm>

  4: 

  5: using namespace std ;

  6: 

  7: void print(int x)//output

  8: { 

  9:     cout << x << " " ;

 10: }

 11: void pVector(const vector<int>& iv) //print vector<int>

 12: {

 13:     for_each(iv.rbegin(),iv.rend(),print) ;

 14: }

15: void _express(int num,int m,vector<int>& iV)

//num:the num need to express

//m: the an’s range can be [1,m]

//iv : used to record the data across the call

 16: {

 17:     if(num<m){// num is a1, find the last num in the express

 18:         if (num){// beacuse a1>0, so to make sure a1!=0

 19:             print(num);     

 20:             //iV.insert(iV.begin(),num) ;

 21:         }

 22:         pVector(iV) ;

 23:         cout << endl ;

 24:         return ; 

 25:     }  

 26:     for(int i=m;i>0;--i){

 27:         iV.push_back(i) ; // chose a num in range [1,m] as an

 28:         _express(num-i,i,iV) ; // an is fined, so to find an-1

 29:         iV.pop_back() ;   //pop the old an

 30:     }

 31: }

 32: void express(int n) 

 33: {

 34:     vector<int> iV ; // used to record the data

 35:     _express(n,n,iV) ;  // n = a1 + a2 + … + an, the max an is n,an in [1,n]   

 36: }
posted @ 2012-03-23 14:13  Better-zyy  阅读(300)  评论(0编辑  收藏  举报