""" 时间复杂度 O(n^3) """ stone = [16,11,7,17,11,7,9,2,17,20,22,7,5,17,6,14,21,2,9,2,15,20,14,6,12,16,9,8,14,5,1,12,4,19,5,14,22,20,13,12,19,14,3,6,17,21,13,17,8,9,18,1,8,12,5,20,2,7,14,22,14,7,12,20,22,2,13,15,9,14,20,13,3,18,8,10,20,10,18,21] N = len(stone) class Solution(object): def stoneGame(self, stone, N): p = [[0 for i in xrange(N)] for j in xrange(N)] s = [[0 if i != j else stone[i] for i in xrange(N)] for j in xrange(N)] for l in xrange(1, N): for i in xrange(N-l): j = i + l p[i][j] = None for k in xrange(i, j): if p[i][j] == None: s[i][j] = s[i][k] + s[k+1][j] p[i][j] = p[i][k] + p[k+1][j] + s[i][j] else: p[i][j] = min(p[i][j], p[i][k] + p[k+1][j] + s[i][j]) return p[0][N-1]
|