Partition of an Integer + Number of partitions

后端 未结 4 788
说谎
说谎 2020-12-18 12:08

A partition of an integer n is a way of writing n as a sum of positive integers. For

example, for n=7, a partition is 1+1+5. I need a program that finds all the

4条回答
  •  清酒与你
    2020-12-18 12:26

    Essentially what Codor said, plus you don't need to recurse further into part() once you found a partition of the target length since they would be longer:

    #include 
    #include 
    
    using namespace std;
    
    void print (vector& v, int level){
        for(int i=0;i<=level;i++)
            cout << v[i] << " ";
        cout << endl;
    }
    
    void part(int n, vector& v, int level, int r){
        int first; /* first is before last */
    
        if(n<1) return ;
        v[level]=n;
        if( level+1 == r ) {
            print(v, level);
            return;
        }
    
        first=(level==0) ? 1 : v[level-1];
    
        for(int i=first;i<=n/2;i++){
            v[level]=i; /* replace last */
            part(n-i, v, level+1, r);
        }
    }
    
    int main(){
        int num,r;
        cout << "Enter a number:";
        cin >> num;
        cout << "Enter size (r):";
        cin >> r;
    
        vector v(num);
    
        part(num, v, 0, r);
    }
    

    Output:

    Enter a number:5
    Enter size (r):2
    1 4
    2 3
    

提交回复
热议问题