# [LeetCode]Unique Binary Search Trees, 解题报告

## 题目

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

## 思路

n == 0 时，空树的个数必然为1，因此dp[0] = 1

n == 1 时，只有1这个根节点，数量也为1，因此dp[1] = 1

n == 2时，有两种构造方法，如下图所示：

n == 3时，构造方法如题目给的示例所示，dp[3] = dp[0] * dp[2] + dp[1] * dp[1] + dp[2] * dp[0]

## 代码

```import java.util.Scanner;

public class UniqueBinarySearchTrees {
public static int numTrees(int n) {
int i, j, dp[] = new int[n + 1];

if (n == 0) return 1;

dp[0] = dp[1] = 1;

for (i = 2; i <= n; i++) {
dp[i] = 0;
for (j = 0; j < i; j++) {
dp[i] += dp[j] * dp[i - j - 1];
}
}

return dp[n];
}

public static void main(String[] args) {
int n, num;
Scanner cin = new Scanner(System.in);

while (cin.hasNext()) {
n = cin.nextInt();
num = numTrees(n);

System.out.println(num);
}

cin.close();
}
}
```

• 本文已收录于以下专栏：

CSDN出品，立即查看！

## LeetCode 96:Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For ex...

## Unique Binary Search Trees II

Unique Binary Search Trees II@(leetcode)[枚举, DFS]Given an integer n, generate all structurally uniqu...
• lqcsp
• 2016-08-21 15:54
• 204

## LeetCode96:Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For ex...

## LeetCode || Unique Binary Search Trees

Unique Binary Search Trees  Total Accepted: 11525 Total Submissions: 32497My Submissions ...

## LeetCode_Unique Binary Search Trees

LeetCode_Unique Binary Search Trees 解题思路

## leetcode -- Unique Binary Search Trees II

leetcode -- Unique Binary Search Trees II

## [leetcode] 95. Unique Binary Search Trees II 解题报告

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)