classSolution{public:intnumTrees(intn){// dp[i] := the number of unique BST's that store values 1..ivector<int>dp(n+1);dp[0]=1;dp[1]=1;for(inti=2;i<=n;++i)for(intj=0;j<i;++j)dp[i]+=dp[j]*dp[i-j-1];returndp[n];}};
1 2 3 4 5 6 7 8 91011121314
classSolution{publicintnumTrees(intn){// dp[i] := the number of unique BST's that store values 1..iint[]dp=newint[n+1];dp[0]=1;dp[1]=1;for(inti=2;i<=n;++i)for(intj=0;j<i;++j)dp[i]+=dp[j]*dp[i-j-1];returndp[n];}}
1 2 3 4 5 6 7 8 910
classSolution:defnumTrees(self,n:int)->int:# dp[i] := the number of unique BST's that store values 1..idp=[1,1]+[0]*(n-1)foriinrange(2,n+1):forjinrange(i):dp[i]+=dp[j]*dp[i-j-1]returndp[n]