Meta 面试中的树形 DP 题目。本文通过员工休假优化问题,展示树形动态规划的应用csvosupport* 助你掌握高级 DP 技巧
📋 问题背景
公司组织结构是一棵树,每个员工有休假天数需求。规则:
- 如果员工休假,其直接下属不能休假
- 求最大总休假天
🎯 核心思路
这是经典的树DP 问题,类打家劫舍 III"
解法:树DP
class Employee:
def __init__(self, id, vacation_days):
self.id = id
self.vacation_days = vacation_days
self.subordinates = []
def max_vacation_days(root):
def dfs(node):
if not node:
return (0, 0)
# take: 当前员工休假
# not_take: 当前员工不休
take = node.vacation_days
not_take = 0
for sub in node.subordinates:
sub_take, sub_not_take = dfs(sub)
# 如果当前员工休假,下属不能休
take += sub_not_take
# 如果当前员工不休假,下属可选择休或不休
not_take += max(sub_take, sub_not_take)
return (take, not_take)
take, not_take = dfs(root)
return max(take, not_take)
时间复杂度: O(n) 空间复杂度: O(h)
🚀 扩展:多层限
def max_vacation_with_constraints(root, max_consecutive):
def dfs(node, parent_took, consecutive_count):
if not node:
return 0
# 选择1:当前员工休
take = 0
if not parent_took and consecutive_count < max_consecutive:
take = node.vacation_days
for sub in node.subordinates:
take += dfs(sub, True, consecutive_count + 1)
# 选择2:当前员工不休假
not_take = 0
for sub in node.subordinates:
not_take += dfs(sub, False, 0)
return max(take, not_take)
return dfs(root, False, 0)
💼 csvosupport 助力
树形 DP - 状态定义和转移 *优化技 - 记忆化搜 扩展能力 - 处理复杂约束
联系 csvosupport,专DP 面试辅助
*标签 #Meta #动态规#树形DP #VO辅助 #面试辅助 #一亩三分地
需要面试真题? 立刻联系微信 Coding0201,获得真题。