Leetcode oj:unique binary search Trees (unique binary searching tree)

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 first is to use recursion to solve, but see the label is DP problem, think about, the number of BST, 0 ~ k-1 can be divided into two intervals, and then can be generated BST, so K of the number of BST is equal to K left and right can be divided into BST the sum of the flight, the amount, a bit around the mouth amount, The code is a little clearer, look at the code:

1 classSolution {2  Public:3     intNumtrees (intN) {4vector<int>ret;5         if(n = =0)return 0;6Ret.reserve (n +1);7ret[0] =1;8          for(inti =1; I <= N; ++i) {9             if(I <3){TenRet[i] =i; One                 Continue; A             } -              for(intj =0; J < I; ++j) { -Ret[i] + = ret[j] * ret[i-j-1]; the             } -         } -         returnRet[n]; -     } +};

Leetcode oj:unique binary search Trees (unique binary searching tree)

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.