【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.
   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
 : 1,2,...n ,  i  : result = sigma(( )*( ))
 DP :
class Solution {
public:
    int numTrees(int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if( n <= 1)
            return n;
        return cal(1,n);
    }
    int cal(int st,int end)
    {
        if(st >= end)
            return 1;
        int sum = 0;
        for(int i = st; i <= end; i++)
        {
            sum += cal(st,i-1) * cal(i+1,end);
        }
        return sum;
    }
};
class Solution {
public:
    int numTrees(int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if( n <= 1)
            return n;
        int *dp = new int[n+1];
        dp[0] = dp[1] = 1;
        
        for(int i = 2; i <= n; i++)
        {
            dp[i] = 0;
            for(int j = 0; j < i; j++)
            {
                dp[i] += dp[j]*dp[i-j-1];
            }
        }
        
        int res = dp[n];
        delete [] dp;
        dp = NULL;
        return res;
    }
   
};
the DP method has good run-time complexity!

좋은 웹페이지 즐겨찾기