首页 > 代码库 > [LeetCode]96 Unique Binary Search Trees

[LeetCode]96 Unique Binary Search Trees

https://oj.leetcode.com/problems/unique-binary-search-trees/

http://blog.csdn.net/linhuanmars/article/details/24761459

public class Solution {
    public int numTrees(int n)
    {
        // See
        // http://blog.csdn.net/linhuanmars/article/details/24761459
        
        // r0 = 0;
        // r1 = 1;
        // r2 = 2;
        // r3:
        // 有三个点,都可以为根
        // 如果以1为根,左边为c0,右边为c2  的乘积
        // 如果以2位根,左边为c1,右边为c1  的乘积
        // 如果以3为根,左边为c2,右边为c0  的乘积
        // 递推公式
        // c[n+1] = sum( c[i] * c[n - i] ) // i value: [0, n]
        
        if (n <= 0)
            return 0;
            
        int[] r = new int[n + 1];
        r[0] = 1;
        r[1] = 1;
        
        for (int i = 2; i < r.length ; i ++)
        {
            for (int j = 0 ; j < i ; j ++)
            {
                r[i] += r[j] * r[(i - 1) - j];
            }
        }
        return r[n];
    }
}


[LeetCode]96 Unique Binary Search Trees