algorithm - N 个相同的球在 A 个不同的盒子中的组合

标签 algorithm combinatorics

int f(int n,int a,int x)
{
        if(a==1)
        {
            if(n>=0 && n<=x)  //HERE WAS ERROR,sorry
                return 1;
            else 
                return 0;
        }

        int ans=0;

        for(int i=0;i<=x;i++)
            ans += f(n-i,a-1,x);

    return ans;
}

您好! enter image description here

例子:

enter image description here

这是算法,但是它花费了很多时间。 也许您知道解决此问题的更快方法?非常感谢,抱歉让您担心。

最佳答案

你需要的是动态规划。您需要记住函数 f 对于那些已经计算过的参数的值。它也可以像这样在没有递归的情况下实现:

int f(int n,int a,int x)
{
    int q[1000][50]; // to simplify and not use dynamic allocation assume that a < 50 and n < 1000

    q[0][0] = 1;
    for (int i = 1; i < 1000; ++i)
        q[i][0] = 0;

    for (int i = 1; i <= a; ++i)
    {
        for (int j = 0; j <= n; j++)
        {
            int t = 0;
            for (int l = 0; l <= j && l <= x; ++l)
                t += q[j - l][i-1];
            q[j][i] = t;
        }
    }

    return q[n][a];
}

这只是简单的技术演示。可以再优化一次,可以预先计算t-sum,消除l的循环。而且你不必存储整个表 q,你只需要两层,它会减少内存使用。所以结果将如下所示:

int f(int n,int a,int x)
{
    int q[1000][2]; // to simplify and not use dynamic allocation assume n < 1000

    q[0][0] = 1;
    for (int i = 1; i < 1000; ++i)
        q[i][0] = 0;

    int current = 1;
    for (int i = 1; i <= a; ++i)
    {
        int t = 0;
        for (int j = 0; j <= n; j++)
        {
            t += q[j][1 - current];
            if (j > x)
                t -= q[j - x - 1][1 - current];

            q[j][current] = t;
        }
        current = 1 - current;
    }

    return q[n][1 - current];
}

所以最终需要 O(a*n) 的时间来计算。

PS:请注意,answer 可以是一个巨大的数字,它可以溢出任何原生整数类型。

关于algorithm - N 个相同的球在 A 个不同的盒子中的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8078653/

相关文章:

java - 是否有可能在 O(1) 中得到 m 个字符长度组合的第 k 个元素?

algorithm - 最大多样性 : translate an heuristic algorithm in C (or pseudocode)

java - 打印 4 x 5 板的所有配置,其中包含 1's and 0' s,尽可能不包含三个 1's in a row or diagonally, while filling as many 1' s

matlab - 使用 MATLAB 生成所有重复组合

string - 最多 n 个位置不同的字符串数?

c++ - 获取线段和 2^n 网格之间的所有交点(以整数表示)

python - 在 python 中寻找一些关于组合学的指导

algorithm - 一道关于开关控制的算法题

c++ - 为什么这个层序遍历在 O(n) 时间内运行?

algorithm - 该算法的渐近时间复杂度