【Leetcode】Unique Binary Search Trees (DP)

来源:互联网 发布:国家省市区四级联动js 编辑:程序博客网 时间:2024/05/22 12:56

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.

卡特兰数模型

递推式:f(i)=f(i)+f(j)*f(i-j-1)

public int numTrees(int n) {int[] result = new int[n + 1];result[0] = 1;result[1] = 1;for (int i = 2; i <= n; i++) {for (int j = 0; j < i; j++) {result[i] = result[i] + result[j] * result[i - j - 1];}}return result[n];}


0 0
原创粉丝点击