N求和的不同组合

Different combinations of summands of N

本文关键字:组合 和的 求和      更新时间:2023-10-16

程序应写出,N的自然和数有多少种不同的组合。所有的和数不大于,则K (N,K<=120)。我的程序只包含递归:

int  F (int x,int s)  // s- total number, which is necessary to lay down the terms of
{
if (s == 0) // when total number == 0
    {
        ans++;   
        return 0;
    }
for (int i=x;i<=min(k,s);i++) // x - previous term
    F(i,s-i);           // we add a new summand -> subtract that number from the amount
}

和主体部分:

int main ()
{
 cin >> n>> k;
 F(1,n);
 cout << ans;
}

那么,你能帮我把程序做得快一点吗?

您可以添加记忆。对于固定的x和s,不需要多次计算F。它需要稍微更改代码(使F实际返回计算值,而不是增加一个数值),并添加一个数组来保存已经计算过的值。

这是一个有趣的练习;

int F (int x,int s)
{
    static map< int, map< int, int > > table;
    if( (x==s) || (s==0) ) return 1;
    if( x > s ) return 0;
    auto itr1 = table.find(x);
    if( itr1 != table.end() )
    {
        auto& sub = itr1->second;
        auto itr2 = sub.find(s);
        if( itr2 != sub.end() )
        {
            return itr2->second;
        }
    }
    int ans=1;
    for ( int i=x; i<s; ++i )
        ans += F(i,s-i);
    table[x][s]=ans;
    return ans;
}