(Leetcode 95+96)Unique Binary Search Trees 动态规划 分治
2016-05-28 17:24
477 查看
1. (Leetcode 96)Unique Binary Search Trees
第一道题目,求1-n的数字组成BST的所有方法数BST即二叉排序树,其先序遍历序列为从小到大排列。
题目原文:
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
解法:动态规划
拿到n个数字后,从中依次选取一个作为根结点,遍历其左子树和右子树的所有方法的所有笛卡尔积组合,累加,作为该点作为根节点的方法数。
注释比较详细,直接看代码吧
int numTrees(int n) { //申请n+1个空间是因为空子树也是一种形式 vector<int> res(n+1, 0); //初始化 n = 0 和 n = 1的情况分别代表该子树为空或该子树只有一个节点,都只有一种解法,故而都置为1 res[0] = res[1] = 1; //动态规划,从n = 2开始循环,一直到 n for(int k = 2;k <= n;++k){ res[k] = 0; //首先初始化为0 //凡是 1-k 的数字都可以作为根节点,这时需要循环所有左子树和右子树的组合,累计当节点个数为k时构成BST的方法数 for(int i = 1;i <= k;++i){ //循环i,即将i作为根节点时累加所有的方法数,其中i = 1时左子树为空,i = k时右子树为空 res[k] += res[i-1] * res[k-i]; //此处用乘法,即左子树组合和右子树组合笛卡尔积 } } return res ; }
2. (Leetcode 95)Unique Binary Search Trees ||
第二道题目,相对于第一道题目加大了难度,需要我们不仅仅对BST的原理比较了解,还要求返回构造出的BST的根节点。题目给出了数据结构。下面我把我自己实现的代码,包括main函数和数据结构分享给大家,程序是可以运行的。基本思路是分治和递归,也可以用动态规划来做,下面代码是基于分治法的。
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; //Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: //-------------------------------------------------------- //分治递归解法 vector<TreeNode *> generateTree(int from, int to) { vector<TreeNode *> ret; if(to - from < 0) //此时子树为空,方法数为1 ret.push_back(NULL); if(to - from == 0) //此时子树只有一个节点,方法数为1 ret.push_back(new TreeNode(from)); //当方法数不为1时进行循环 if(to - from > 0) { //i作为根节点,遍历其左右子树的各种情况 for(int i = from; i <= to; i++) { vector<TreeNode *> l = generateTree(from, i-1); //左子树集合 vector<TreeNode *> r = generateTree(i+1, to); //右子树集合 //左子树和右子树的全组合 for(int j = 0; j < l.size(); j++) { for(int k = 0; k < r.size(); k++) { TreeNode * h = new TreeNode(i); h->left = l[j]; h->right = r[k]; ret.push_back(h); } } } } return ret; } vector<TreeNode *> generateTrees(int n) { if(n == 0) return vector<TreeNode*>(); return generateTree(1, n); } }; int main(){ int n = 3; Solution sul; vector<TreeNode*> res = sul.generateTrees(n); getchar(); return 0; }
相关文章推荐
- C++动态规划之最长公子序列实例
- C++动态规划之背包问题解决方法
- C#使用动态规划解决0-1背包问题实例分析
- MIT Introduction to Algorithms 学习笔记(六)
- 动态规划
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++ 动态规划
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList