题解 | #放苹果#
放苹果
https://www.nowcoder.com/practice/4f0c1e21010e4d849bde5297148e81d9
def distribute_apples(M, N):
"""
将M个苹果分配到N个盘子的分法数,修正了M < N的情况
"""
# 创建一个二维列表,用于存储中间结果,以减少重复计算
dp = [[-1 for _ in range(N + 1)] for _ in range(M + 1)]
def helper(M, N):
# 边界条件处理
if M < 0:
return 0
if M == 0 or N == 1:
return 1
if M < N:
return helper(M, M) # 当苹果数少于盘子数时,直接使用苹果数作为盘子数进行计算
# 如果这个结果已经计算过了,直接返回
if dp[M][N] != -1:
return dp[M][N]
# 递归计算
dp[M][N] = helper(M, N - 1) + helper(M - N, N)
return dp[M][N]
return helper(M, N)
M, N = map(int, input().split())
print(distribute_apples(M, N))
