算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 不同的二叉搜索树,我们先来看题面:
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;
}
}
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];
}
}