classSolution: defmaxValueOfCoins(self, piles: List[List[int]], k: int) -> int: @cache deffunc1(count,pos,l): if l == 0: return count if pos > len(piles)-1: return0 ans = func1(count,pos+1,l) for i inrange(min(len(piles[pos]), l)): count += piles[pos][i] l -= 1 ans = max(ans,func1(count,pos+1,l)) return ans return func1(0,0,k)
思路:
从左到右依次处理,考虑所有情况。当前栈取出 i 个数,0 <= i < min(len(piles[pos]), l) ,其中 pos 指当前数组第 pos 个栈, l 是指剩余要取多少个数。
代码二:代码一优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defmaxValueOfCoins(self, piles: List[List[int]], k: int) -> int: @cache deffunc1(pos,l): if l == 0: return0 if pos > len(piles)-1: return0 ans = func1(pos+1,l) count = 0 for i inrange(min(len(piles[pos]), l)): count += piles[pos][i] l -= 1 ans = max(ans,count + func1(pos+1,l)) return ans return func1(0,k)
思路:
代码二相比代码一, count 计数不作为函数传递参数。
代码三:动态规划
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defmaxValueOfCoins(self, piles: List[List[int]], k: int) -> int: f = [0] * (k + 1) sum_n = 0 for pile in piles: n = len(pile) for i inrange(1, n): pile[i] += pile[i - 1] # 提前计算 pile 的前缀和 sum_n = min(sum_n + n, k) for j inrange(sum_n, 0, -1): # 优化:j 从前 i 个栈的大小之和开始枚举 # w 从 0 开始,物品体积为 w+1 f[j] = max(f[j], max(f[j - w - 1] + pile[w] for w inrange(min(n, j)))) return f[k]