Leetcode Unique Binary Search Trees

來源:互聯網
上載者:User

標籤:

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

For example,
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
解題思路:

dynamic programming. 最重要的就是找規律!!!

這類找combination/permutation的題都需要找找規律。 n = 0 n = 11 n = 2   1                  2     \                /      2            1 n = 3 1           3    3      2     1    \        /     /       / \       \     3    2    1      1   3      2    /     /        \                    \   2   1          2                   3  定義f(n)為unique BST的數量,以n = 3為例: 構造的BST的根節點可以取{1, 2, 3}中的任一數字。 如以1為節點,則left subtree只能有0個節點,而right subtree有2, 3兩個節點。所以left/right subtree一共的combination數量為:f(0) * f(2) = 2 以2為節點,則left subtree只能為1,right subtree只能為2:f(1) * f(1) = 1 以3為節點,則left subtree有1, 2兩個節點,right subtree有0個節點:f(2)*f(0) = 2 總結規律:f(0) = 1f(n) = f(0)*f(n-1) + f(1)*f(n-2) + ... + f(n-2)*f(1) + f(n-1)*f(0) Let count[i] be the number of unique binary search trees for i. The number of trees are determined by the number of subtrees which have different root node. For example,
i=0, count[0]=1 //empty treei=1, count[1]=1 //one treei=2, count[2]=count[0]*count[1] // 0 is root            + count[1]*count[0] // 1 is rooti=3, count[3]=count[0]*count[2] // 1 is root            + count[1]*count[1] // 2 is root            + count[2]*count[0] // 3 is rooti=4, count[4]=count[0]*count[3] // 1 is root            + count[1]*count[2] // 2 is root            + count[2]*count[1] // 3 is root            + count[3]*count[0] // 4 is root......Recurrence formula: i=n, count[n] = sum(count[0..k]*count[k+1...n]) 0 <= k < n-1
base case: count[0] = 1 count[1] = 1

Java code:

public class Solution {    public int numTrees(int n) {        int[] count = new int[n+1];        count[0] = 1;        count[1] = 1;                for(int i = 2; i<= n; i++){            for(int j = 0; j < i; j++){                count[i] += count[j] * count[i-1-j];            }        }        return count[n];    }}

Reference:

1. http://www.programcreek.com/2014/05/leetcode-unique-binary-search-trees-java/

2. http://bangbingsyb.blogspot.com/2014/11/leetcode-unique-binary-search-trees-i-ii.html


 

Leetcode Unique Binary Search Trees

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.