以下是代码,当我运行solution.shoppingOffers([2,5],[[3,0,5],[1,2,10],[3,2])时,python显示:RecursionError :比较中超过了最大递归深度。
class Solution(object):
def shoppingOffers(self, price, special, needs):
"""
:type price: List[int]
:type special: List[List[int]]
:type needs: List[int]
:rtype: int
"""
return self.helper(price, special, needs, 0)
def helper(self, price, special, needs, index):
if index == len(special):
return self.dot_product(price, needs)
else:
offer = special[index]
flag = False
for index, value in enumerate(needs):
if value < offer[index]:
flag = True
break
if flag:
return self.helper(price, special, needs, index + 1)
else:
return min(self.helper(price, special, needs, index + 1), offer[-1] + self.helper(price, special, self.minus(needs, offer), index))
def dot_product(self, prices, needs):
return sum(i[0] * i[1] for i in zip(prices, needs))
def minus(self, needs, offer):
return [i[0] - i[1] for i in zip(needs, offer)]
答案 0 :(得分:1)
我不知道程序的背景,但是您要覆盖for循环中的index变量是否正确?
for index, value in enumerate(needs):
if value < offer[index]:
flag = True
break
那样,自
以来,递归可能会无限进行if index == len(special):
return self.dot_product(price, needs)
从不成立。在这种情况下,更改变量名称可能会解决问题。