`

Leetcode - 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个节点的BST的结构数等于从1到n依次为root节点对应的BST个数,记录中间结果避免重复计算。

 

public class Solution {

   // Method 2
   //dp[i] : number of unique BSTs which store value [1,i]
    public int numTrees(int n) {
        if (n <= 0)
            return 0;
        int[] dp = new int[n + 1];
        dp[0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) // select j as root
                dp[i] += dp[j - 1] * dp[i - j];
        }
        return dp[n];
    }
 
    // Method 1
    public int numTrees(int n) {
        if (n <= 0)
            return 0;
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            int mid = (i - 1) / 2;
            for (int j = 0; j <= mid; j++)
                dp[i] += 2 * dp[j] * dp[i - 1 - j];//编码过程中i-1-j写成n-1-j,调试了好一会
            if (i % 2 == 1)
                dp[i] -= dp[mid] * dp[mid];
        }
        return dp[n];
    }
}

 

分享到:
评论
2 楼 likesky3 2015-04-16  
嗯,不考虑对称的实现更优,代码清晰,更不容易出错。
1 楼 qb_2008 2015-04-14  
需要算对称吗?反正都是O(n^2).

相关推荐

Global site tag (gtag.js) - Google Analytics