[Leetcode] Unique Binary Search Trees @ Python

Source: Internet
Author: User

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

For example,

Given n = 3, there is a total of 5 unique BST ' s.

   1         3     3      2      1    \//      /\           3     2     1      1   3      2    /     /       \                    2     1         2                 3
The main idea is simple, is to calculate how many different two forks looking for a tree to meet the pre-sequence traversal is 1,2,3...N conditions
Idea: Each tree is composed of root node, left subtree, right subtree, once the root node is determined to be X,
Zuozi can only be constituted by 1,2,3...x-1, and the right subtree is composed of X+1,X+2...N, which can
[Method 1] fall generation solution;
classSolution:#@return An integer    defnumtrees (self, n): DP= [1, 1, 2]        ifN < 3:returnDp[n] DP+ = [0 forIinchRange (n-2)]         forIinchRange (3, n+1):             forJinchRange (i): Dp[i]+ = Dp[j]*dp[i-j-1]        returnDp[n]
[Method 2] Recursive solution
class Solution:     # @return an integer    def numtrees (self, N):         = [1, 1, 2]        ifreturn  dp[n]        = 0          for inch range (N):               + = Self.numtrees (i) *self.numtrees (n-i-1          )return ans

[Leetcode] Unique Binary Search Trees @ Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.