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
没有做备忘录,否则效率更高。
本题相当于对于n个数,先拿出来一个数做根,剩下的数以各种方式分别给左子树和右子树。
class Solution { public: int numTrees(int n) { int re =0; if(n == 1||n==0)return 1; for(int i = 0 ; i<n ;i++) re += numTrees(i)*numTrees(n-i-1); return re; } };
posted on 2014-03-17 21:49 pengyu2003 阅读(132) 评论(0) 编辑 收藏 举报