123456789101112131415161718192021222324252627282930313233343536 |
- def can_distribute_gifts(prices, fans):
- total_price = sum(prices)
- if total_price % fans != 0:
- return False
- target_price = total_price // fans
- prices.sort(reverse=True) # 从大到小排序,有助于更快找到解
- def backtrack(start, groups):
- if start == len(prices):
- return True
- for i in range(fans):
- if groups[i] + prices[start] <= target_price:
- groups[i] += prices[start]
- if backtrack(start + 1, groups):
- return True
- groups[i] -= prices[start]
- # 如果当前组为空,且后续的组也为空,则无需继续尝试
- if groups[i] == 0:
- break
- return False
- groups = [0] * fans
- return backtrack(0, groups)
- # 示例
- prices1 = [5, 4, 1, 3, 2, 3, 2]
- fans1 = 4
- print(can_distribute_gifts(prices1, fans1)) # 输出: True
- prices2 = [1, 2, 2, 2, 2]
- fans2 = 3
- print(can_distribute_gifts(prices2, fans2)) # 输出: False
|