原题链接在这里:https://leetcode.com/problems/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.
1 3 3 2 1 / / / 3 2 1 1 3 2 / / 2 1 2 3
题解:
DP问题.
初始化, dp[0] = 1, dp[1] = 1. 当n=0时,返回1,只返回一个空树,当n=1时,返回1,只有一个节点的树.
状态转移,对于总共 i 个点, 它的返回值应该是对于每个点的不同左子树的个数dp[j] * 不同右子树的个数dp[i-1-j]的和. j在[0,i-1]区间内.
答案dp[n].
Time Complexity: O(n^2). Space:O(n).
AC Java:
1 class Solution { 2 public int numTrees(int n) { 3 int [] dp = new int[n+1]; 4 dp[0] = 1; 5 dp[1] = 1; 6 for(int i = 2; i<=n; i++){ 7 for(int j = 0; j<i; j++){ 8 dp[i] += dp[j]*dp[i-j-1]; 9 } 10 } 11 return dp[n]; 12 } 13 }