96. 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

 

 

Hide Similar Problems
 (M) Unique Binary Search Trees II
 

链接: http://leetcode.com/problems/unique-binary-search-trees/

6/5/2017

抄的答案,DP做法

注意

1. 第11行当中的两个部分dp[j], dp[i-j-1]都是之前算好了的,是总数为i的条件下成树的个数

2. i从1-n都是在为n来做准备的

 1 public class Solution {
 2     public int numTrees(int n) {
 3         if (n <= 0) {
 4             return 0;
 5         }
 6         int[] dp = new int[n + 1];
 7         dp[0] = 1;
 8         
 9         for (int i = 1; i <= n; i++) {
10             for (int j = 0; j < i; j++) {
11                 dp[i] += dp[j] * dp[i - j - 1]; // j: elements less than i, i - j - 1: elements larger than i
12             }
13         }
14         return dp[n];
15     }
16 }

参考

http://www.cnblogs.com/yrbbest/p/4437169.html

别人的答案以及解释

https://discuss.leetcode.com/topic/8398/dp-solution-in-6-lines-with-explanation-f-i-n-g-i-1-g-n-i

更多讨论

https://discuss.leetcode.com/category/104/unique-binary-search-trees

posted @ 2017-06-06 01:24  panini  阅读(126)  评论(0编辑  收藏  举报