LeetCode happy brush title thirty-six days --96. Unique Binary Search Trees

96. Unique Binary Search Trees
Medium

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

Example:

Input: 3
Output: 5
Explanation:
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
Three method solve this problem:
1.C++ version DP
mistake:
this part * + I misused.Cause large problem
dp[i] += dp[j] * dp[i - 1 - j];
 
  
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<stack>
#include<climits>
#include<unordered_map>
#include<bits/stdc++.h>
//
using namespace std;

class Solution {
public:
    int numTrees(int n) {
        // how many trees if the total tree has dp[i] nodes.
        vector<int> dp(n + 1);
        dp[0] = dp[1] = 1;
        for (int i = 2; i < n + 1; i ++) {
            for (int j = 0; j < i; j++) {
                dp[i] += dp[j] * dp[i - 1 - j];
            }
        }
        return dp[n];
    }
};


int main()
{
    Solution1 s;
    cout<<s.Num(5)<<endl;
    return 0;
}

 DP python Version:

class Solution(object):
    def numTrees(self,n):
        dp=[1,1]
        for i in range(2,n+1):
            tmp=0
            for j in range(i):
                tmp+=dp[j]*dp[i-1-j]
            dp.append(tmp)
        return dp[i]

solu=Solution()
print(solu.numTrees(5))

 

 

 

Guess you like

Origin www.cnblogs.com/Marigolci/p/11362491.html