[Dynamic Programming] when the number of binary tree structure

Dynamic programming ideas, DP [i] represents the number of i-th binary tree structure where the nodes may be configured .

Traversing the selected j-th node as the root node, the dp [n] + = dp [j-1] * dp [ij]

class Solution {
public:
    int numTrees(int n) {
        if(n<0)
            return 0;
        int dp[2000]={0};
        dp[0]=1;
        dp[1]=1;
        for(int i=2;i<=n;i++) //结点总个数
        {
            for(int j=1;j<=n;j++) //选取第几个结点作为根结点
            {
                dp[i] += dp[j-1]*dp[i-j]; //dp[左子树个数]*dp[右子树个数]
            }
        }
        return dp[n];
    }
};

 

Guess you like

Origin blog.csdn.net/m0_38033475/article/details/92384106