Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
examples:
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
classSolution1(object): defmaxCoins(self, nums): """ :type nums: List[int] :rtype: int """ path = [] max_path = [path] max = [0] s = [0] D = set() self.find(nums, path, D, s, max, max_path) print(max_path[0]) returnmax[0]
deffind(self, nums, path, D, s, max, max_path): iflen(path) == len(nums): if s[0] > max[0]: max[0] = s[0] max_path[0] = path[:] else: for i inrange(len(nums)): if i notin D: path.append(i) D.add(i) tmp = self.compute(i, nums, D) s[0] += tmp self.find(nums, path, D, s, max, max_path) path.pop() D.remove(i) s[0] -= tmp
defcompute(self, i, nums, D): left, right = 1, 1 for j inrange(i - 1, -1, -1): if j notin D: left = nums[j] break for k inrange(i + 1, len(nums)): if k notin D: right = nums[k] break return left * right * nums[i]
classSolution2(object): defmaxCoins(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) list = self.get(nums) # 转换为n+1个矩阵的表示。每个pair tuple对应矩阵的长和宽。 print(list) n += 1 m = [[None] * n for i inrange(n)] # 声明一个子问题空间是n^2的记忆体 print(m) for i inrange(n): m[i][i] = 0
returnself.recursive(list, m, 0, n - 1)
defget(self, nums): n = len(nums) list = [(1, nums[0])] for i inrange(n): if (i + 1 < n): list.append((nums[i], nums[i + 1])) else: list.append((nums[i], 1)) returnlist
defrecursive(self, list, m, i, j): if m[i][j] isnotNone: return m[i][j] else: max = -1 for k inrange(i, j): a = self.recursive(list, m, i, k) b = self.recursive(list, m, k + 1, j) v = a + b + list[i][0] * list[k][1] * list[j][1] if v > max : max = v m[i][j] = max return m[i][j]