c++ - 使用动态规划计算二项式系数

标签 c++ algorithm recursion dynamic-programming

我写这段代码来求二项式系数nCk:

# include <bits/stdc++.h>
using namespace std;
int c[20][20];
void initialize()
{
    for(int i=0;i<20;i++) 
        for(int j=i;j<20;j++)
            c[i][j]=-1;
}
int binomCoeff(int n,int k)
{
    if(k==0||k==n) return 1;
    if(c[n][k]!=-1)
        return c[n][k];
    return c[n][k] =  binomCoeff(n-1,k-1) + binomCoeff(n-1,k);
}

int main()
{
    initialize();
    cout<<binomCoeff(4,2)<<endl;
}

我是动态规划的新手,所以找不到错误。

最佳答案

您正在为 k(小于或等于 n)使用第二个索引,但仅初始化更大的索引

for(int j=  0  ;j<20;j++)
or
for(int j=  0  ;   j <= i  ;j++)

请注意,此错误将在逐步调试过程中被发现。你为什么忽略这种方法?

附言这里使用的方法是 memoization - “自上而下”的动态规划。您还可以将“自下而上”动态规划实现为练习 - 按顺序填充表格并获得最后一个单元格结果。

关于c++ - 使用动态规划计算二项式系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47836616/

相关文章:

c# - 将具有递归的SQL查询转换为LINQ

c++ - GetFieldValue 时间变量错误

algorithm - Lisp 堆栈溢出边界

c++ - std::async 正在阻塞/暂停父线程

c# - 按顺序打印二叉树

algorithm - 可以在优于 O(n) 的时间内通过纬度/经度计算最近的位置吗?

javascript - 一旦所有嵌套的 promise 都解决了,就触发 Promise.all()

java - Math.random() 使用安全吗?

c++ - 使用带有 CMake 和 Conan 的外部库的 undefined reference

c++ - 在 C++ 中使用文件时出现段错误