我想知道是否还有另一种方法可以像我在这里那样不使用3个嵌套的for循环来解决此问题?我知道,如果在足够大的列表上测试该方法,则以这种方式嵌套循环很可能会引起很多问题。
这是问题:
from typing import List
def can_pay_with_three_coins(denoms: List[int], amount: int) -> bool:
"""Return True if and only if it is possible to form amount, which is a
number of cents, using exactly three coins, which can be of any of the
denominations in denoms.
>>> can_pay_with_three_coins([1, 5, 10, 25], 36)
True
>>> can_pay_with_three_coins([1, 5, 10, 25], 37)
False
"""
这是我的解决方案:
for i in range(len(denoms)):
one_coin = denoms[i]
for j in range(len(denoms)):
another_coin = denoms[j]
for k in range(len(denoms)):
last_coin = denoms[k]
if one_coin + another_coin + last_coin == amount:
return True
return False
我确信还有另一种解决此问题的方法,只是我真的没有想到。
感谢您的帮助!
答案 0 :(得分:4)
这是一个著名的问题,名为3 sum。
此解决方案的时间复杂度为O(n ^ 3),您可以实现O(n ^ 2)的算法,该算法在以下链接中以多种语言进行了解释和实现:
答案 1 :(得分:1)
好吧,让我们用itertools作弊:)
import itertools
from typing import List
def can_pay_with_three_coins(denoms: List[int], amount: int) -> bool:
"""Return True if and only if it is possible to form amount, which is a
number of cents, using exactly three coins, which can be of any of the
denominations in denoms.
>>> can_pay_with_three_coins([1, 5, 10, 25], 36)
True
>>> can_pay_with_three_coins([1, 5, 10, 25], 37)
False
"""
for variant in itertools.permutations(denoms, len(denoms)):
if sum(variant[:3]) == amount:
return True
return False
print(can_pay_with_three_coins([1, 5, 10, 25], 36))
print(can_pay_with_three_coins([1, 5, 10, 25], 37))
print(can_pay_with_three_coins([1, 1, 5, 10, 25], 37))
print(can_pay_with_three_coins([1, 3, 5, 10, 25], 37))
print(can_pay_with_three_coins([20, 20, 20, 50], 60))
输出
True
False
False
False
True