LeetCode Unique Binary Search Trees
2014-03-18 22:05
507 查看
题目:
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.
思想:n个节点除去跟节点还有n-1个节点,左子树的节点数为0,1,...,相应的右子树的节点数为n-1,n-2,...0;
则f(n) = f(0)f(n-1)+f(1)f(n-2)+...+f(n-2)f(n-1)+f(n-1)f(1)
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个节点除去跟节点还有n-1个节点,左子树的节点数为0,1,...,相应的右子树的节点数为n-1,n-2,...0;
则f(n) = f(0)f(n-1)+f(1)f(n-2)+...+f(n-2)f(n-1)+f(n-1)f(1)
class Solution { public: int numTrees(int n) { if(n == 0) return 1; if(n == 1) return 1; if(n >= 2) { int sum = 0; for(int i = 0; i < n; i++) sum += numTrees(i)* numTrees(n-1-i); return sum; } } };
相关文章推荐
- TimerTask()中调用TextView.setText报错原因(非UI线程中 不能访问UI组件)
- 6.Uicolor(颜色类)
- html <marquee>标签
- Request.ServerVariables
- ADT Cannot complete the install because one or more required items could not be found.
- UITableView 实现异步加载图片之改进
- java-----------GUI菜单设计
- iPhone开发应用中关于UITableView详细教程
- UINavigationController详解(四)iOS7新特性
- 优先队列priority_queue
- bluetooth之power on流程
- volatile、内存屏障、Acquire&Release语义 三者的差别和关系(一) —— 之volatile
- 半小时搞定Arduino环境(含蓝牙模块与Android通讯)
- synchronuized详解
- UIKit各类概述
- strusts2request,session取得
- Android学习之Build.xml文件
- android之init进程-uevent
- Android Service 通过 BroadcastReceiver 更新Activity UI
- poj 1904 King's Quest 强联通分量