Problem 2
function VC(v)
# including v
in = 1
for child c of v:
in += min(c.in, c.ex)
# not including v
ex = 0
for child c of v:
ex += c.in
v.in = in
v.ex = ex
return min(v.in, v.ex)
- Base case: for a leaf node
leaf
,leaf.in = 1, leaf.ex = 0
- IH: for node
v
with leavesu1..uk
, assumeui.in, ui.ex
is correct - IS: for node
v
,- Case including:
VC
includingv
does not requireu1..uk
to be included, but including it may be more minimal. IH guaranteesui.in, ui.ex
is correct so take the minimum - Case excluding:
VC
excludingv
requires all ofu1..uk
to be included, so in that case sum all theui.in
values to guarantee counting all cases where children are included
- Case including:
- Time complexity:
Problem 3
def PalindromeDecomposition
# memo[n][n] is a 2-d array whose value is all "N"
# in increasing order of gap
for gap=1..n
for i=0..n-gap-1
j = i + gap
# base case
if i==j
memo[i][j] = Y
continue
# if edges are same, check the inner
if A[i] == A[j]
if memo[i+1][j-1] == Y
memo[i][j] == Y
else
memo[i][j] == N
# if edges are diff, not palindrome
else A[i] != A[j]
memo[i][j] == N
# memo_count[n][n] is a 2-d array whose value is all 0.
# in increasing order of gap
for gap=1..n
for i=0..n-gap-1
j = i + gap
# if the whole length i-j is palindrome, 1
if memo[i][j] == Y
memo_count[i][j] = 1
# if the whole length isn't palindromic...
minPcount = +infty
for k=0..j-i:
# get the minimum palindrome split of all possible splits
min(minPcount, memo[i][i+k-1] + memo[i+k][j])
memo_count[i][j] = minPcount
return memo_count[0][n]
-
Part 1:
- Base case: a length-1 string is a palindrome
- IH1: substring is a palindrome
- IS1: then if , the string is a palindrome
- IH2: substring is not a palindrome
- IS2: then the string cannot be a palindrome
-
Part 2:
- Base case: If the string is a palindrome, then it is the minimum palindromic split of count 1
- IH: palindromic substring count has been computed correctly from all proper substrings of
- IS: the minimum palindromic substring if is the minimum of the sums for
-
Thus proved
-
Part 1 span: as filling a 2-d array with calculation per subarray
-
Part 2 span: as filling a 2-d array with calculation per subarray
-
⇒ Total time complexity: