博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Unique Binary Search Trees
阅读量:4151 次
发布时间:2019-05-25

本文共 1933 字,大约阅读时间需要 6 分钟。

class Solution {//a combinatorial mathematics problem //Firstly, this kind of problem generally can be modeled as famous number, here is catalan number//Secondly, If we do not have such a background, I think it will be totally fine if we can find //the transform equation or the regular pattern.//analysis://we pick a node i as a root in the BST, then the size of left subtree is i-1, and the size of //right tree is n-i, though the number in right tree may be different from 1 2 ... n-i, but actually//it is equal to the sequence of that in such a problem.//Now we should figure out that, if j is not equal to i, is there any duplicate(same) case?//I think there will be no same case, because the root is different that will be enough to prove this.//So, the equation will be f(size)=sum of f(i-1)*f(size-i), where 1<=i<=size. //initialize: f(0)=1, f(1)=1 public:	int DP(int n)	{		if(n <= 1)			return 1;		vector
f(n+1, 0); f[0] = f[1] = 1; for (int size = 2; size <= n; ++size) { for (int i = 1; i <= size; ++i) { f[size] += f[i-1]*f[size-i]; } } return f[n]; } int numTrees(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function return DP(n); }};

second time

class Solution {public:    int numTrees(int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector
> f(n, vector
(n, 0)); for(int i = 0; i < n; ++i) f[i][i] = 1; for(int len = 2; len <= n; ++len) { for(int i = 0; i < n; ++i) { int j = len-1+i; if(j >= n) break; for(int k = i; k <= j; ++k) { if(k == i) f[i][j] += f[k+1][j]; else if(k == j) f[i][j] += f[i][k-1]; else f[i][j] += (f[i][k-1]*f[k+1][j]); } } } return f[0][n-1]; }};

转载地址:http://chxti.baihongyu.com/

你可能感兴趣的文章
PicGo+GitHub:你的最佳免费图床选择!
查看>>
Python GUI之tkinter窗口视窗教程大集合(看这篇就够了)
查看>>
Markdown Emoji表情语法速查表
查看>>
vim的复制粘贴小结
查看>>
Doxygen + Graphviz windows下安装配置(图解)
查看>>
win8 PL2303驱动的问题
查看>>
vim中寄存器使用和vim标记
查看>>
原码、反码和补码
查看>>
STM32中断(转载)
查看>>
STM32 flash操作
查看>>
gedit assertion `lang != NULL' failed
查看>>
ubuntu10.10 教育网 使用ipv6,亲测可用【经过再次验证与修正】
查看>>
google搜索技巧
查看>>
锂电池相关
查看>>
用openjtag&eclipse测试mini2440流水灯程序
查看>>
ARM Linux启动分析----head-armv.S内幕
查看>>
链接脚本
查看>>
openjtag openocd libftd2xx
查看>>
ARM汇编伪指令
查看>>
字节序问题--大端法小端法
查看>>