【Leetcode】96. Unique Binary Search Trees

This is a BST(binary search tree) numbers counting problem but solved in dynamic programing.

https://discuss.leetcode.com/category/104/unique-binary-search-trees

This solution really gives me a shock. Before solving u need do some mathematical deduce in papers and get the dp function, which fantistically! 

class Solution {
public:
    int numTrees(int n) {
        int G[100];
        for(int i = 0; i <= n; i ++)
            G[i] = 0;
        G[0] = G[1] = 1;
        for(int i = 2; i <= n; i ++){
            for(int j = 1; j <= i; j ++)
                G[i] += G[j - 1] * G[i - j];
        }
        return G[n];
    }
};

 

 

posted on 2016-07-06 22:53  暴力的轮胎  阅读(161)  评论(0编辑  收藏  举报

导航