[英]implement DP for a recursive function
I have the following recursive function: 我具有以下递归函数:
typedef unsigned long long ull;
ull calc(ull b, ull e)
{
if (!b) return e;
if (!e) return b;
return calc(b - 1, e - 1) + calc(b - 1, e) - calc(b, e - 1);
}
I want to implement it with dynamic programming (ie using storage). 我想通过动态编程(即使用存储)来实现它。 I have tried to use a map<pair<ull, ull>, ull>
but it is too slow also. 我试图使用map<pair<ull, ull>, ull>
但是它也太慢了。 I couldn't implement it using arrays O(1)
too. 我也不能使用数组O(1)
来实现它。
I want to find a solution so that this function solves quickly for large b, e
s. 我想找到一个解决方案,以便该函数可以快速解决大b, e
s的问题。
Make a table b/e and fill it cell by cell. 制作一张桌子b / e并逐格填写。 This is DP with space and time complexity O(MaxB*MaxE). 这是具有时空复杂度O(MaxB * MaxE)的DP。
Space complexity may be reduced with Ante's proposal in comment - store only two needed rows or columns. 使用Ante的注释可以减少空间的复杂性-仅存储两个需要的行或列。
0 1 2 3 4 5
1 0 3 . . .
2 . . . . .
3 . . . . .
4 . . . . .
You might want to take a look at this recent blog posting on general purpose automatic memoization . 您可能想看看最近有关通用自动备忘的 博客文章 。 The author discusses various data structures, such std::map
, std::unordered_map
etc. Warning: uses template-heavy code. 作者讨论了各种数据结构,例如std::map
, std::unordered_map
等。警告:使用大量模板代码。
If a bottom up representation is what you want then this would do fine. 如果您想要一个自下而上的表示形式,那会很好。
Fill up the table as MBo has shown 如MBo所示填写表格
This can be done as: 可以这样完成:
for e from 0 to n:
DP[0][e] = e
for b from 0 to n:
DP[b][0] = b
for i from 1 to n:
for j from 1 to n:
DP[i][j] = DP[i-1][j-1] + DP[i-1][j] - DP[i][j-1]
now your answer for any b,e is simply DP[b][e] 现在您对任何b,e的答案就是DP [b] [e]
You can implement in O(n^2) (assuming n as max number of values for b and e ) by using a 2 dimensional array. 您可以使用二维数组在O(n ^ 2)中实现(假定n为b和e的最大值)。 Each current value for i,j would depend on the value at i-1,j and i-1,j-1 and i,j-1. i,j的每个当前值将取决于i-1,j和i-1,j-1和i,j-1的值。 Make sure you handle cases for i=0, j=0. 确保处理i = 0,j = 0的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.