All problems
Tree DP Minimum Vertex Cover
Problem
Compute the size of a minimum vertex cover of a tree with dynamic programming.
Root the tree at node 0. For each node keep take[v] = 1 + sum of min over children and skip[v] = sum of take over children, because an uncovered edge forces the child into the cover. Return the better of take and skip at the root. edges is a list of [u, v] pairs.
Hint
If a node stays out of the cover, every child must be inside it.
Test cases
case 1
in: [4,[[0,1],[1,2],[2,3]]]
expected: 2
case 2
in: [4,[[0,1],[0,2],[0,3]]]
expected: 1
case 3
in: [1,[]]
expected: 0
case 4
in: [5,[[0,1],[1,2],[1,3],[3,4]]]
expected: 2
case 5
in: [3,[[0,1],[1,2]]]
expected: 1
Starter codePython
def tree_dp_min_vertex_cover(n, edges):
# Your code here
pass5 test cases · run your code against them in the editor