leetcode96. Unique Binary Search Trees
2016-07-10 11:29
483 查看
题目链接:https://leetcode.com/problems/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.
题目大意:给一个数字n,那么有n个结点的二叉查找树共有多少棵。结点val对应从1到n。
这道题看了很多博客,也算是搞懂了,总结一下就是:
选取一个结点为根,就把结点切成左右子树,以这个结点为根的可行二叉树数量就是左右子树可行二叉树数量的乘积,所以总的数量是将以所有结点为根的可行结果累加起来。
大概也是使用动态规划,n=3的过程如下:
代码如下:
题目:
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,那么有n个结点的二叉查找树共有多少棵。结点val对应从1到n。
这道题看了很多博客,也算是搞懂了,总结一下就是:
选取一个结点为根,就把结点切成左右子树,以这个结点为根的可行二叉树数量就是左右子树可行二叉树数量的乘积,所以总的数量是将以所有结点为根的可行结果累加起来。
大概也是使用动态规划,n=3的过程如下:
//r1+=r0*r0;r1=1 //r2+=r0*r1 r2=1 //r2+=r1*r0 r2=2 //r3+=r0*r2 r3=2 //r3=r1*r1 r3=3 //r3+=r2*r9 r3=5
代码如下:
public class Solution { public int numTrees(int n) { if(n ==0 || n ==1) return 1; int res[] =new int[n+1]; res[0]=1; for(int i =1 ; i <= n ; i++){ for(int j = 0; j < i; j++){ res[i] += res[j]*res[i-j-1]; } } return res ; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 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
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解