96. Unique Binary Search Trees

来源:互联网 发布:瑞士莲 费列罗 知乎 编辑:程序博客网 时间:2024/05/22 21:02

Given an integer 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

The idea is Suppose we know the solution from 1 to n-1, and we want to know about n;

F(n) = 0;

We could choose a number X from 1 to n to be the root, and all the numbers in the left subtree i < X and in the right tree i > X

There are (i - 1) number in the left tree and (n - i) number in the right tree.

F(n) += F(i - 1) * F(n - i) for i from 1 to N 

Code:

public class Solution {    public int numTrees(int n) {        int[] dp = new int[n + 1];        dp[1] = 1;        dp[0] = 1;        if(n <= 1) return 1;        for(int i = 2; i <= n; i++){            for(int k = 0; k < i; k++){                dp[i] += dp[k]*dp[i-k-1];            }        }        return dp[n];    }}


in the above code k stands for how many number in the left tree and (i - k - 1) stands for how many number in the right tree. 





0 0
原创粉丝点击