[leetcode]96. Unique Binary Search Trees

[leetcode]96. Unique Binary Search Trees


Analysis

intern intern intern—— [每天刷题并不难0.0]

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?
在这里插入图片描述
动态规划解决,状态转移方程:
DP[n] = DP[0]DP[n-1]+DP[1]DP[n-2]+…+DP[i-1]DP[n-i]+…DP[n-1]DP[0];

Implement

class Solution {
public:
    int numTrees(int n) {
        vector<int> DP(n+1, 0);
        DP[0] = DP[1] = 1;
        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];
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/85045635