forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-cost-to-merge-stones.py
36 lines (34 loc) · 1.18 KB
/
minimum-cost-to-merge-stones.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Time: O(n^3)
# Space: O(n^3)
# memoization (top-down dp)
class Solution(object):
def mergeStones(self, stones, K):
"""
:type stones: List[int]
:type K: int
:rtype: int
"""
def dp(prefix, K, i, j, k, lookup):
if (i, j, k) in lookup:
return lookup[i, j, k]
if i == j:
result = 0 if k == 1 else float("inf")
else:
if k == 1:
result = dp(prefix, K, i, j, K, lookup) + \
prefix[j+1] - prefix[i]
else:
result = float("inf")
for mid in xrange(i, j, K-1):
result = min(result, dp(prefix, K, i, mid, 1, lookup) +
dp(prefix, K, mid+1, j, k-1, lookup))
lookup[i, j, k] = result
return result
if (len(stones)-1) % (K-1):
return -1
lookup = {}
prefix = [0]
for x in stones:
prefix.append(prefix[-1]+x)
result = dp(prefix, K, 0, len(stones)-1, 1, lookup)
return result if result != float("inf") else 0