LeetCode (Unique Binary Search Trees)

来源:互联网 发布:图片上传到淘宝变模糊 编辑:程序博客网 时间:2024/06/14 21:04

Problem:

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

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


原创粉丝点击