【菜鸟er】经典题目_划分整数

#include <bits/stdc++.h>
using namespace std;
#define MAX_N 400
int dp[MAX_N][MAX_N];
int part_sum(int ,int );//输出种数
int part_print(int,int,int,int sec[],int);
int max_part;
int sec[MAX_N];
int main()
{
    int n,m;
    cin>>n>>m;
    cout<<"1:递归"<<endl;
    int sum = part_sum(n,m);
    cout<<sum<<endl;


    cout<<"2:DP"<<endl;
    int ndp=n,mdp=m;
    for(int i = 0;i<=100;i++){
        for(int j = 0;j<=100;j++)
            dp[i][j] = 0;
            dp[i][1] = 1;
    }
    dp[0][0]=1,dp[0][1]=1,dp[1][0]=1,dp[1][1]=1;
    for(int n = 2;n<=ndp;n++){
        for(int m = 1;m<=n;m++){
            if(n-m<=m){
                dp[n][m] = dp[n][m-1] + dp[n-m][n-m];
            }
            else{
                dp[n][m] = dp[n][m-1] + dp[n-m][m];
            }
        }
    }
    cout<<dp[ndp][mdp]<<endl;


    cout<<"3.可输出表达式的递归:"<<endl;
    max_part = m;


    for(int i = 1;i<=m;i++){
        cout<<"种数:"<<part_print(n,i,1,sec,0)<<endl;
    }


    return 0;
}


int part_sum(int n,int k)
{
    if(k == 1) return 1;
    else if(k >  n) return part_sum(n,n);
    else if(k == n) return (part_sum(n,k-1) +1 );//这一种是 n = n;
    else if(k <  n) return (part_sum(n,k-1) + part_sum(n-k,k) );
}


int part_print(int n,int m,int start,int sec[MAX_N],int index)
{
    //n:整数,m:分成m份 start:从start开始分类 数组sec[]:存储分类的情况  index:数组下标,从0开始


    if(m == 1){
        sec[index] = n;
        for(int i = 0;sec[i]!=0;i++){
            cout<<sec[i]<<" ";
        }
        cout<<endl;
        return 1;
     }
     int sum = 0;


     for(int i = start;i<=n/m;i++){
        sec[index] = i;
        sum = sum + part_print(n-i,m-1,i,sec,index+1);
     }
     return sum;
}

阅读更多
个人分类: acmer
所属专栏: acmer菜鸟学习工具
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭