Leetcode 题解 - Dynamic Programming 1D
题解
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 range[i, 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 memo[n] != null -> return memo[n]
- Ask subproblems for answers:
a. for i in [1,n]:
i. left = dfs(i-1), right = dfs(n-i)
ii. result = left * right
4. Update memo[n] and return result
时间复杂度:O(n**2)
另可以用正向填表:把dfs的flow反过来,从底层子问题开始往大计算,最终计算到顶层问题
High Level
- Initialize memo[n + 1]
- Fill out base case -> memo[0] = memo[1] = 1
- for i in [2,n]:
a. Use Transition Rule -> for j in [1, i]:
i. memo[i] += memo[j-1] * memo[i - j]
4. return memo[n]
时间复杂度:O(n**2)
思路
High Level
-
Initialize memo
-
Call dfs(s,n)
dfs(s,n)
- Base case -> n <= 1 return 1
- If memo[n] != null -> return memo[n]
- Ask Subproblems for answers
a. if x is valid (not 0) -> result += memo[n-1]
b. if xx is valid (<= 26) -> result += memo[n-2]
4. Update memo and return result
转载自:https://juejin.cn/post/7303832834624045066