LC 343 & LC 96


Solution to LeetCode 343 Integer Break and LeetCode 96 Unique Binary Search Trees

LeetCode 343

Integer Break (Medium) [link]

Define dp[i] as the maximum product of splitting number i. From 1, 2, ..., j, we can get dp[i] in two ways: 1) j * (i-j) if (i-j) cannot be split, 2) j * dp[i-j] if (i-j) can be split, where dp[i-j] is the maximum product of splitting number i-j. And we store the maximum value of the two.

The recurrence relation is dp[i] = max(dp[i], max((i-j) * j, dp[i-j] * j)). The base case: dp[2] = 1. Note that since the base case starts from 2, i starts from 3, j ends in i-1.

class Solution:
    def integerBreak(self, n: int) -> int:
        dp = [0] * (n+1)
        dp[2] = 1

        for i in range(3, n+1):
            for j in range(1, i-1):
                dp[i] = max(dp[i], max(j * dp[i-j], j * (i-j)))

        return dp[n]

LeetCode 96

Unique Binary Search Trees (Medium) [link]

When n= 1, there is 1 unique BST. When n=2, there are 2 unique BSTs. When n =3, there are 5 unique BSTs. Then we can notice that the number of unique BSTs can actually be calculated by the results of previous subproblems. (5 = 2 + 2 + 1).

When n = 3, dp[3] = dp[2] * dp[0] + dp[1] * dp[1] + dp[0] * dp[2].

  • If root is 1, the number of unique BST is: the number of unique BSTs of 2 elements(left) * the number of unique BSTs of 0 element (right).
  • If root is 2, the number of unique BST is: the number of unique BSTs of 1 elements (left) * the number of unique BSTs of 1 element (right).
  • If root is 3, the number of unique BST is: the number of unique BSTs of 0 element (left) * the number of unique BSTs of 2 elements (right).

Define dp[i] as the number of unique BSTs composed of nodes of 1 to i.

The recurrent relation is dp[i] += dp[j-1] * dp[i-j], where dp[j-1] is the number of unique BSTs of the left subtree of the root j, dp[i-j] is the number of unique BSTs of the right subtree if the root j. (e.g. dp[3] += dp[0] * dp[2] when j = 1).

The base case dp[0]=1 because the above recurrent relation is doing multiplication. And dp[1]=1. The final answer is stored in dp[-1].

class Solution:
    def numTrees(self, n: int) -> int:
        dp = [0] * (n+1)
        dp[0] = 1
        dp[1] = 1
        for i in range(2,n+1):
            for j in range(1,i+1):
                dp[i] += dp[j-1] * dp[i-j]
        return dp[-1]

  TOC