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; }