leetcode--Unique Binary Search Trees

来源:互联网 发布:没网能看电视的软件 编辑:程序博客网 时间:2024/06/11 10:36

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,计算1到n可以组成多少排序二叉树

分类:二叉树


解法1:动态规划。假设flag[n]记录了给定n能组成的排序二叉树数目。

对于1到n个节点,我们逐个看,先是以1为根节点,其余2到n个节点为右子树,则总共有flag[0]*flag[n-1]种组合方式

再以2为根节点,1为左子树,其余3到n为右子树,则总共有flag[1]*flag[n-2]种组合方式

依次类推,以i为根节点,则1到i-1为左子树,i+1到n为右子树,则总过有flag[i-1]*flag[n-i]中组合方式

最后全部相加,就是flag[n]

另外我们要初始化flag[0]为1,flag[1]为1


根据上面的说法,我们可以从1到n遍历,逐个为根节点,对于当前选定的根节点i,前面1到i-1一共有i-1个数,我们可以递归计算

同样,i+1到n一共n-i个数,我们可以递归计算

在计算过程中为了避免左右两边的重复计算(因为对于每个数目,我们只要算一次就好了),我们要剪枝

利用flag[]数组来存储已经计算过的结果,如果已经计算过可以直接返回

[java] view plain copy
  1. public class Solution {  
  2.     public int numTrees(int n) {  
  3.         int[] flag = new int[n+1];  
  4.         flag[1] = 1;          
  5.         return helper(n,flag);   
  6.     }  
  7.       
  8.     public int helper(int n,int[] flag){  
  9.         if(n==0return 1;  
  10.         if(flag[n]!=0return flag[n];    
  11.         for(int i=0;i<n;i++){  
  12.             int left = helper(i,flag);  
  13.             int right = helper(n-i-1,flag);  
  14.             flag[n] += left*right;  
  15.         }  
  16.         return flag[n];  
  17.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46455531