The description of the question is in the following link:
My code:
class Solution:
def numTrees(self, n: int) -> int:
if n ==1:
return 1
elif n ==2 :
return 2
else:
TotalNumberList = [1]*(1+n)
for Length in range(2,n+1):
TotalSum = 0
for Index in range(Length):
NumberDevideByThisIndex = TotalNumberList[Index]*TotalNumberList[Length-1-Index]
TotalSum += NumberDevideByThisIndex
TotalNumberList[Length] = TotalSum
return TotalNumberList[n]
Explanation: It actually does not matter if the value is from 1 to n or otherwise, as long as they are sorted by some order. The logic is that for each particular value we choose, the list is divided into two parts: left list and right list. We just need to multiply the number in the left list and right list to get the total number of trees we have for this particular number. As for all the ordered list with the same length, they all have the same number of trees, hence we just need to start from the number of trees with one and zero, then gradually calculate from one to n and return the nth one in the list.