test.py 1020 B

123456789101112131415161718192021222324252627282930313233343536
  1. def can_distribute_gifts(prices, fans):
  2. total_price = sum(prices)
  3. if total_price % fans != 0:
  4. return False
  5. target_price = total_price // fans
  6. prices.sort(reverse=True) # 从大到小排序,有助于更快找到解
  7. def backtrack(start, groups):
  8. if start == len(prices):
  9. return True
  10. for i in range(fans):
  11. if groups[i] + prices[start] <= target_price:
  12. groups[i] += prices[start]
  13. if backtrack(start + 1, groups):
  14. return True
  15. groups[i] -= prices[start]
  16. # 如果当前组为空,且后续的组也为空,则无需继续尝试
  17. if groups[i] == 0:
  18. break
  19. return False
  20. groups = [0] * fans
  21. return backtrack(0, groups)
  22. # 示例
  23. prices1 = [5, 4, 1, 3, 2, 3, 2]
  24. fans1 = 4
  25. print(can_distribute_gifts(prices1, fans1)) # 输出: True
  26. prices2 = [1, 2, 2, 2, 2]
  27. fans2 = 3
  28. print(can_distribute_gifts(prices2, fans2)) # 输出: False