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. I couldn't implement it using arrays O(1)
too.
I want to find a solution so that this function solves quickly for large b, e
s.
Make a table b/e and fill it cell by cell. This is DP with space and time complexity O(MaxB*MaxE).
Space complexity may be reduced with Ante's proposal in comment - store only two needed rows or columns.
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.
If a bottom up representation is what you want then this would do fine.
Fill up the table as MBo has shown
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]
You can implement in O(n^2) (assuming n as max number of values for b and e ) by using a 2 dimensional array. Each current value for i,j would depend on the value at i-1,j and i-1,j-1 and i,j-1. Make sure you handle cases for i=0, j=0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.