leetcode_96. Unique Binary Search Trees

来源:互联网 发布:淘宝首页导航栏尺寸 编辑:程序博客网 时间:2024/06/07 07:13

题目:

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

解题思路:

设一共有n个节点,可能的unique BST 为DP(n)。跟节点可以是任意一个元素,如第i个元素。根节点左侧为1~i-1个元素,右侧为第i+1到第n个元素。而左侧又是一个 i-1 个数的一个子树可以以任意一个0~i-1 的数字为根节点。所以左右子树的可能为DP(i-1)*DP(n-i)种可能。所以每个DP(n) 用前面的DP的值计算得来。而每个DP又循环每个值作为根相加。

DP(0) = 1; DP(1) = 1;

代码如下:

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

注意DP中的元素初始化为0,以为后面要累加。