今天和大家聊的问题叫做 不同的二叉搜索树,我们先来看题面:
https://leetcode-cn.com/problems/unique-binary-search-trees/
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
题意
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
样例
解题
递归子问题
假设 n 个节点存在二叉排序树的个数是 G (n),令 f(i) 为以 i 为根的二叉搜索树的个数,则
G(n)=f(1)+f(2)+f(3)+f(4)+...+f(n),
f(i)=G(i−1)∗G(n−i)
class Solution { public int numTrees(int n) { if (n == 0 || n == 1) return 1; int res = 0; for (int i = 1; i <= n; i++) { res += numTrees(i - 1) * numTrees(n - i); } return res; } }
动态规划
从dp[0],dp[1]开始逐渐向后扩大
public class Solution { public 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]; } }
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。