Tuesday, September 24, 2013

Unique Binary Search Trees

Q:
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

A:
递归调用 方法,
public class UniqueBinarySearchTrees {
    public int numTrees(int n) {
        // DP method
        if (n == 0 || n == 1)
            return 1;
        if (n == 2)
            return 2;
        int sum = 0;
        for (int i = 1; i <= n; i++) { // choose i as the root.
            sum = sum + (numTrees(i - 1) * numTrees(n - i));
        }
        return sum;
    }
}
---------------------------------------------第二遍-------------------------------
这次是真正的DP

class Solution {
public:
    int numTrees(int n) {
        vector<int> A(n+1,0);
        A[0]=1;
        for(int i = 1; i<n+1;++i)
            for(int rootVal =1; rootVal <=i ; ++rootVal)
                A[i] += A[rootVal-1] * A[i-rootVal];
        return A[n];
    }
};



Mistakes:
1: 注意,左右两边,是相乘的关系,(乘法原理)

















No comments:

Post a Comment