问题
This is a classical game where two players play following game:
There are n coins in a row with different denominations. In this game, players pick a coin from extreme left or extreme right (they blindly pick from any extreme with a probability of .5, both of them are dumb). I just want to count the expected sum of player who starts the game.
For this I want to sum up all the possible combinations of values a player can have. I am using a recursive solution which sums up all the possible outcome values but it is having overlapping sub-problems. I want to make it efficient and want to memoize these overlapping sub-problems.
I am not able to collect the logic to execute it. Please someone help.
回答1:
Idea is for each row subinterval to store sums for both players.
Let F(start, end)
denote possible sums of first player playing on interval [start, end]
. Similar define S(start, end)
. We can store possible sums with a probabilities of sums with a dictionary, like {2: 0.25, 5: 0.25, 6: 0.5}
.
Than recursions hold:
F(start, end) = {row[end] +sum: p/2, for sum,p in S(start, end-1)} +
{row[start]+sum: p/2, for sum,p in S(start+1, end)}
S(start, end) = {sum: p/2, for sum,p in F(start, end-1)} +
{sum: p/2, for sum,p in F(start+1, end)}
F(start, end) = {row[start]: 1} if start == end
S(start, end) = {} if start == end
This can be calculated by increasing interval length:
for length = 0 to row_length-1:
for start = 1 to row_length - length:
calculate `F(start, start+length)` and `S(start, start+length)`
Dictionaries F(1, row_length)
and S(1, row_length)
are used to calculate expected sum.
来源:https://stackoverflow.com/questions/12873730/sum-all-possible-values-a-player-can-have-in-a-two-player-game