题解





State: (n)
State(n): how many unique BST to form with n nodes from 1, n, where i is the selected root

for range 1, i -1, this is calculated range for unique BST
for rangei, n-i, this is the another range for unique BST
multiply the answer for above two ranges for final result
High Level:
- Initialize memo with n + 1 slots
- call dfs(n)
dfs(n):
- Base case (n <= 1) -> return 1
- If memon != null -> return memon
- Ask subproblems for answers:
a. for i in 1,n:
i. left = dfs(i-1), right = dfs(n-i)
ii. result = left * right
- Update memon and return result

时间复杂度:O(n**2)
另可以用正向填表:把dfs的flow反过来,从底层子问题开始往大计算,最终计算到顶层问题
High Level
- Initialize memon + 1
- Fill out base case -> memo0 = memo1 = 1
- for i in 2,n:
a. Use Transition Rule -> for j in 1, i:
i. memoi += memoj-1 * memoi - j
- return memon

时间复杂度:O(n**2)


思路


High Level
-
Initialize memo
-
Call dfs(s,n)
dfs(s,n)
- Base case -> n <= 1 return 1
- If memon != null -> return memon
- Ask Subproblems for answers
a. if x is valid (not 0) -> result += memon-1
b. if xx is valid (<= 26) -> result += memon-2
- Update memo and return result

