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

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

LeetCode: Unique Binary Search Trees

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 地址: 算法:动态规划,dp[i]记录有i个节点的搜索树数量,则$dp[i+1]=\sum_{j=0}^{i-1}dp[j]*dp[i-1-j]$,代码:
1 class Solution { 2 public: 3     int numTrees(int n) { 4         vector
dp(n+1); 5 dp[0] = 1; 6 dp[1] = 1; 7 for(int i = 2; i <= n; ++i){ 8 int sum = 0; 9 for(int j = i-1; j >= 0; --j){10 sum += (dp[j] * dp[i-1-j]);11 }12 dp[i] = sum;13 }14 return dp[n];15 }16 };

第二题:

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,

Given n = 3, your program should return all 5 unique BST's shown below.

1         3     3      2      1    \       /     /      / \      \     3     2     1      1   3      2    /     /       \                 \   2     1         2                 3 地址: 算法:与上一题不同,本题要求构造出所有的解。用递归完成的,代码:
1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     vector
generateTrees(int n) {13 TreeNode *p = NULL;14 if(n <= 0) return vector
(1,p);15 return generateSubtrees(1,n);16 }17 vector
generateSubtrees(int s, int e){18 TreeNode *p = NULL;19 if(s > e) return vector
(1,p);20 if(s == e) {21 p = new TreeNode(s);22 return vector
(1,p);23 }24 vector
result;25 for(int i = s; i <= e; ++i){26 vector
left = generateSubtrees(s,i-1);27 vector
right = generateSubtrees(i+1,e);28 for(int left_i = 0; left_i < left.size(); ++left_i)29 for(int right_i = 0; right_i < right.size(); ++right_i){30 p = new TreeNode(i);31 p->left = left[left_i];32 p->right = right[right_i];33 result.push_back(p);34 }35 }36 return result;37 }38 };

 

 
posted on
2014-08-31 21:43 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/boostable/p/leetcode_unique_binary_search_trees.html

你可能感兴趣的文章
js设计模式 --- 装饰设计模式
查看>>
Flask源代码阅读笔记(一)——应用启动
查看>>
IOS精品源码,仿探探UIButton封装iOS提示弹框迅速引导页自定义导航栏
查看>>
setState的一个Synthetic Event Warning
查看>>
通读Python官方文档之wsgiref(未完成)
查看>>
2017回顾
查看>>
Maven3 快速入门
查看>>
《编写可读代码的艺术》——表面层次的改进
查看>>
RxJS Observable - 一个奇特的函数
查看>>
大型WEB架构设计
查看>>
小程序TAB列表切换内容动态变化,scrollview高度根据内容动态获取
查看>>
swoole_table 实现原理剖析
查看>>
你需要知道面试中的10个JavaScript概念
查看>>
TiDB RC4 Release
查看>>
阿里云有对手了!CDN横评:腾讯云优势明显
查看>>
Ajax常用方法
查看>>
Glide 简单流程分析
查看>>
Hmily 2.0.3 发布,高性能异步分布式事务 TCC 框架
查看>>
烟花年下岁月
查看>>
Java源码阅读之HashMap - JDK1.8
查看>>