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
给出一个n,求1-n个数可以组成多少种二叉查找树
思路:对每一个root为k的树有多少种来说,那就就需要知道左子树的根k-1可以组成多少种树,同时右子树根为n-1-k时候有多少种树,结果就是左边和右边的种类数相乘
动态规划
1 class Solution(object): 2 def numTrees(self, n): 3 flag = [0]*(n+1) 4 flag[0],flag[1] = 1,1 5 for i in range(2,n+1): 6 for j in range(i): 7 flag[i] += flag[j]*flag[i-1-j] 8 return flag[n] 9