-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDp96.java
More file actions
51 lines (48 loc) · 1.27 KB
/
Dp96.java
File metadata and controls
51 lines (48 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package dynamicprogramming;
/**
* @ProjectName: leetcode
* @Package: dynamicprogramming
* @ClassName: Dp96
* @Author: markey
* @Description:
* 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
*
* 示例:
*
* 输入: 3
* 输出: 5
* 解释:
* 给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
*
* 1 3 3 2 1
* \ / / / \ \
* 3 2 1 1 3 2
* / / \ \
* 2 1 2 3
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/unique-binary-search-trees
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Date: 2020/1/5 10:42
* @Version: 1.0
*/
public class Dp96 {
public int numTrees2(int n) {
int[] G = new int[n + 1];
G[0] = 1;
G[1] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 1; j <= i; ++j) {
G[i] += G[j - 1] * G[i - j];
}
}
return G[n];
}
public int numTrees(int n) {
long C = 1;
for (int i = 0; i < n; ++i) {
C = C * 2 * (2 * i + 1) / (i + 2);
}
return (int) C;
}
}