Unique Binary Search Trees

题目:

Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?

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 = 0时候,只有1种
当n = 1时候,只有1中
当n = 2时候,有1为root的情况,是1x1种,2为root的情况是1x1种
当n = 3时候,有1为root的情况,左子树有0个结点,右子树有2个结点
            有2为root的情况,左子树1个,右子树1个
            有3为root的情况,左子树2个,右子树0个
说起来就是f[0] * f[n - 1] + f[1] * f[n - 2] + f[2] * f[n - 3]
所以是一个动态规划,求和问题,是求所有可能情况的和

解法:

class Solution {
public:
    /**
     * @paramn n: An integer
     * @return: An integer
     */
    int numTrees(int n) {
        // write your code here
        vector<int> count(n + 1, 0);
        count[0] = 1;
        count[1] = 1;
        for (int i = 2; i <= n; i++) {
            int temp = 0;
            for (int j = 0; j < i; j++) {
                temp += count[j] * count[i - j - 1];
            }
            count[i] = temp;
        }
        return count[n];
    }
};

results matching ""

    No results matching ""