# Stone Game

There is a stone game.At the beginning of the game the player picks n piles of stones in a line.

The goal is to merge the stones in one pile observing the following rules:

1. At each step of the game,the player can merge two adjacent piles to a new pile.
2. The score is the number of stones in the new pile.

You are to determine the minimum of the total score.

For [4, 1, 1, 4], in the best solution, the total score is 18:

1. Merge second and third piles => [4, 2, 4], score +2
2. Merge the first two piles => [6, 4]，score +6
3. Merge the last two piles => [10], score +10


Other two examples:
[1, 1, 1, 1] return 8
[4, 4, 5, 9] return 43

class Solution:
# @param {int[]} A an integer array
# @return {int} an integer
def stoneGame(self, A):
# memory search
if not A:
return 0
f = [[-1]*len(A) for i in xrange(len(A))]
for i in xrange(len(A)):
f[i][i] = 0
cost = [0]*(len(A)+1)
for i in xrange(1, len(A)+1):
cost[i] = cost[i-1] + A[i-1]
return self.search(A, f, cost, 0, len(A) - 1 )

def search(self, A, f, cost, start, end):
if f[start][end] >= 0:
return f[start][end]
import sys
f[start][end] = sys.maxint
for k in xrange(start,end):
left = self.search(A, f, cost, start, k)
right = self.search(A, f, cost,  k+1, end)
f[start][end] = min(f[start][end], left + right + cost[end+1] - cost[start])

return f[start][end]

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客