题目连接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

解题思路:
首先需要明白什么是二叉搜索树,二叉搜索树又叫二叉排序树,二叉查找树,它是一种对排序和查找都很有用的特殊二叉树。
二叉搜索树的定义:
二叉搜索树或者是一颗空树,或者是具有如下性质的二叉树:
二叉搜索树是递归定义的,所以此题可以使用递归进行构造所有的二叉搜索树,具体算法如下:
解法一:递归+记忆化搜索
递归函数实现如下:
AC代码:
- class Solution {
- static int[][] dp;
- public static int numTrees(int n) {
- dp= new int[n+2][n+2];
- return numTrees(1,n);
- }
- public static int numTrees(int left,int right){
- if (dp[left][right]!=0){//已经计算过,直接返回
- return dp[left][right];
- }
- if (left>right){
- dp[left][right]=1;
- return 1;
- }
-
- int result =0;
- for (int i =left;i<=right;i++){
- int leftNums = numTrees(left,i-1);
- int rightNums = numTrees(i+1,right);
- result+=leftNums*rightNums;
- }
-
- dp[left][right]=result;
- return result;
- }
- }

解法二:动态规划
AC代码:
- class Solution {
- public static int numTrees(int n) {
- int[] dp = new int[n+1];
- dp[0]=dp[1]=1;
- for (int i =2;i<=n;i++){
- for (int j = 1;j<=i;j++){
- dp[i]+=dp[j-1]*dp[i-j];
- }
- }
- return dp[n];
- }
- }