Leet Code, leetcode
For numbers n (greater than 1), how many binary search tree (BST sequence) from 1 to n )?
When n = 3, the BST sequence is:
1 3 3 2 1
\///\\
3 2 1 3 2
//\\
2 1 2 3
Five types.
Analysis:
When N = 1, the BST sequence is
1
/\
Null
1 Type
When N = 2, the BST sequence is
1 2
\/
2 1
2 types
When N = 3, the BST sequence is
1 3 3 2 1
\///\\
3 2 1 3 2
//\\
2 1 2 3
5 types
When N = 4, the BST sequence is
1 4 2 3
\ + /\
2, 3, 4 (5) 1, 2, 3 (5) (1) 1, 4 (2) (2) 1, 2 4 (1)
5 + 5 + 1*2 + 2*1 = 14
When N = 5, the BST sequence is
1 2 3 4
\/\/\/\
2, 3, 4, 5 (14 types) (1 type) 1 3, 4, 5 (5 types) (2 types) 1, 2, 5 (5 types) 1, 2, 3 5 (1 type)
5
/
1, 2, 3, 4 (14 types)
Therefore, count (5) = 14 + 1*5 + 2*2 + 5*1 + 14 = 42
There seems to be a recursive relationship. Consider DP to solve it.
Find the rule and find the recurrence formula:
If S (n) is set to n, then,
S (1) = 1
S (2) = 2
S (3) = S (0) * S (2) + S (1) * S (1) + S (2) * S (0) = 5
S (4) = S (0) * S (3) + S (1) * S (2) + S (2) * S (1) + S (3) * S (0) = 14
Not hard to find,
S (N) = Sum {S (K-1) * S (N-K), where K in [1, N]}
After obtaining the recursive formula, the next step is to write the code:
public class Solution { public int NumTrees(int n) { if(n <= 0) {return 1;}// - dp arrayvar dp = new int[n+1];dp[0] = 1;dp[1] = 1;for(var j = 2; j <= n; j++){// i: 1.. j// dp[j] = sum (dp[i-1] * dp[j-i])var s = 0;for(var i = 1; i <= j; i++){s += dp[i-1] * dp[j-i];}dp[j] = s;}return dp[n]; }}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.