问题
I want to maximize the expression 5-8+7*4-8+9
and answer is 200 after splitting this way
(5 − ((8 + 7) × (4 − (8 + 9)))).
It can be solved by using Matrix-chain multiplication algorithm.
It gives correct answer if expression has only '+' and '*' operator
Let's take expression 5+2*4
1 2 3
1 5 7 28
2 - 2 8
3 - - 4
It's a 3X3 Matrix in which (1,1) is 5 ,(2,2) is 2 and (3,3) is 4 and if i want to know M[1][2] or M[1][3] then
M[1][2] = M[1][1] o M[2][2]
M[1][3] = max(M[1][1] o M[2][3],M[1][2] o M[3][3])
can someone help me to find the right method in case of '-' operator.
回答1:
Not sure whether it can be solved with your algorithm, but here is how I would have solved it.
Assume you have to simplify some expression: a # b # c # d # e, where # is some operation (# can be different). I would approach it with recursion (and memoization). On the first step of the recursion I will try to insert parenthesis at every possible position and to calculate expression after this expression:
(a # b) # c # d # e=X # c # d # ea # (b # c) # d # e=a # Y # d # ea # b # (c # d) # e=a # b # Z # ea # b # c # (d # e)=a # b # c # V
So you basically just decreased 5 operator expression to a bunch of 4 operator expressions. Memoization will be helpful if 2 expression are the same. You finish your recursion when there is just one number (in this case you compares it with maximum and update maximum).
Note that for your 5 operator expression you do not even need memoization.
来源:https://stackoverflow.com/questions/37711709/maximizing-arithmetic-expression