problem:
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 3Tree Dynamic Programming
thinking:
(1)求数量,用DP
(2)刚开始用递归,提交超时
(3)DP的思路是遍历所有子结构,用一个数组保存中间结果,加速求解过程。
code:
DP:
class Solution { public: int numTrees(int n) { vector<int> num; num.push_back(1); for(int i=1; i<=n; i++){ num.push_back(0); if(i<3) num[i]=i; else{ for(int j=1; j<=i; j++) num[i]+=num[j-1]*num[i-j]; } } return num[n]; } };
leetcode || 96、Unique Binary Search Trees
原文地址:http://blog.csdn.net/hustyangju/article/details/45072723