Unique Binary Search Trees (leetcode)
2014-11-03 16:39
363 查看
题目:
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.
题解:递归,为了避免递归的时间浪费,用空间换取时间方法来做,即把每次结果都用数组保存,计算下一个数据时,只需要查数组即可快速得到哦结果。
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
题解:递归,为了避免递归的时间浪费,用空间换取时间方法来做,即把每次结果都用数组保存,计算下一个数据时,只需要查数组即可快速得到哦结果。
#include<iostream> using namespace std; int numTrees(int n) { int *tempResult=new int[n+1]; tempResult[0]=1; tempResult[1]=1; for(int i=2;i<=n;i++) { tempResult[i]=0; for(int j=0;j<(i>>1);j++) { tempResult[i]+=tempResult[j]*tempResult[i-1-j]; } tempResult[i]*=2; if(i&1==1)//如果i是奇数 tempResult[i]+=tempResult[i>>1]*tempResult[i>>1]; } /*上面的属于屏蔽掉的这部分的优化,即只需要计算一半,另一半对称。 //如计算n=5,tempResult[0]*tempResult[4]和tempResult[4]*tempResult[0]是等价的, //只需要最后重新计算tempResult[2]*tempResult[2]即可 for(int i=2;i<=n;i++) { tempResult[i]=0; for(int j=0;j<i;j++) { tempResult[i]+=tempResult[j]*tempResult[i-1-j]; } }*/ int result=tempResult ; delete []tempResult; return result; } int main() { cout<<numTrees(5)<<endl; system("pause"); return 0; }
相关文章推荐
- leetcode第一刷_Unique Binary Search Trees
- Leetcode108: Unique Binary Search Trees II
- 【LeetCode】Unique Binary Search Trees
- Leetcode Unique Binary Search Trees II
- LeetCode-M-Unique Binary Search Trees
- LeetCode之Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees II
- Leetcode_96_Unique Binary Search Trees
- LeetCode||95. Unique Binary Search Trees II
- leetcode Unique Binary Search Trees II java
- leetcode-Unique Binary Search Trees II
- LeetCode(96) Unique Binary Search Trees
- [LeetCode] 122: Unique Binary Search Trees II
- 【LEETCODE】95-Unique Binary Search Trees II
- leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法
- LeetCode——Unique Binary Search Trees
- 2 Unique Binary Search Trees II_Leetcode
- leetcode question 95: Unique Binary Search Trees II
- leetcode 96: Unique Binary Search Trees
- [leetcode] Unique Binary Search Trees @ Python