LeeCode - Unique Binary Search Trees
2016-01-05 15:10
537 查看
题目:
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. 没有节点,BST (Binary Search Tree)为1个, 即空树
2. 有一个节点,BST为1个,即自身为根节点
3. 有二个节点,BST为2个,1为root,左为空,右为2;2为root,左为1,右为空,其实就是dp[0]*dp[1] + dp[1]*dp[0]
1 2
\ /
2 1
4. 有三个节点
可以推出dp[3] = dp[0]*dp[2] + dp[1]*dp[1] + dp[2]*dp[0]
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
思路:
找规律
1. 没有节点,BST (Binary Search Tree)为1个, 即空树
2. 有一个节点,BST为1个,即自身为根节点
3. 有二个节点,BST为2个,1为root,左为空,右为2;2为root,左为1,右为空,其实就是dp[0]*dp[1] + dp[1]*dp[0]
1 2
\ /
2 1
4. 有三个节点
1 1 2 3 3 \ \ / \ / / 3 2 1 3 2 1 / \ / \ 2 3 1 2
可以推出dp[3] = dp[0]*dp[2] + dp[1]*dp[1] + dp[2]*dp[0]
package bst; public class UniqueBinarySearchTrees { public int numTrees(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 0; j < i; ++j) { dp[i] += dp[j] * dp[i - 1 - j]; } } return dp ; } public static void main(String[] args) { // TODO Auto-generated method stub UniqueBinarySearchTrees u = new UniqueBinarySearchTrees(); System.out.println(u.numTrees(3)); } }
相关文章推荐
- iOS 密码输入框(UITextField)
- Word Frequency
- poj 2034 Anti-prime Sequences(dfs)
- easy ui window 相关属性
- 解决ORA-00824: cannot set sga_target due to existing
- mac xcworkspace xcodebuild
- Request failed: unacceptable content-type: text/html" AFNetworking - 芒果iOS开发
- UIView之endEditing方法
- yuicompressor 与 maven结合,打包,压缩js,css
- Java [Leetcode 232]Implement Queue using Stacks
- Java [Leetcode 232]Implement Queue using Stacks
- LinkedBlockingQueue的put,add跟offer的区别(转)
- Arduino PWM的探究
- UML建模之时序图(Sequence Diagram)
- Leetcode215: Distinct Subsequences
- HDU 4027 Can you answer these queries?(线段树)
- UISearchBar光标偏移设置
- break与continue区别
- 让UI失业的网站,各种安卓常用图标。
- IOS开发UI篇--YXFilmSelectView(一个酷炫的电影选票View)