[leetcode] Unique Binary Search Trees
2013-08-18 21:20
302 查看
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.
如果想做一个非递归的,就用动态规划去做,代码如下:
效率比递归的要高很多很多!!
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
class Solution { public: int numTrees(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if(n==0) return 1; else{ int num=0; for(int i=0 ; i<n ; i++) num+=numTrees(i)*numTrees(n-i-1); return num; } } };
如果想做一个非递归的,就用动态规划去做,代码如下:
class Solution { public: int numTrees(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int (*p)[2]=new int[n+1][2]; memset(p,0,sizeof(int)*(n+1)*2); int num; p[0][0]=1; p[0][1]=1; for(int i=1 ; i<=n ; i++){ num=0; for(int j=0 ; j<i ; j++) num+=p[j][0]*p[i-j-1][1]; p[i][0]=num; p[i][1]=num; } return p [0]; } };
效率比递归的要高很多很多!!
相关文章推荐
- 【LeetCode】Unique Binary Search Trees && II
- LeetCode: Unique Binary Search Trees II
- 【LeetCode】Unique Binary Search Trees I && II
- 【leetcode】【96】Unique Binary Search Trees
- LeetCode || Unique Binary Search Trees
- [leetcode刷题系列]Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- LEETCODE: Unique Binary Search Trees II
- [Leetcode] Unique Binary Search Trees I,II
- [Leetcode] Unique Binary Search Trees
- LeetCode95 Unique Binary Search Trees II
- leetcode:Unique Binary Search Trees II
- Leetcode_95 Unique Binary Search Trees II
- leetcode_c++:树: Unique Binary Search Trees(096)
- [LeetCode]Unique Binary Search Trees I&II
- LeetCode Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees, Solution
- [leetcode]95. Unique Binary Search Trees II
- LEETCODE —— Unique Binary Search Trees [动态规划]
- LeetCode *** 95. Unique Binary Search Trees II