LeetCode學習篇十五——Unique Binary Search Trees

題目: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

這道題一開始起來以爲只是生成不同的二分樹,所以想着排列組合就可以解決,看清楚題意後才發現是二分查找樹,需要滿足左結點小於根結點,右結點大於根結點,利用動態規劃,從數字1到n,每個數字都可以作爲根結點,所以是一層循環,然後當根結點爲i時,其生成樹情況爲小於它的結點的子樹乘於大於它的結點的子樹的積的和,類似與乘法原理。
例如:當n爲4,count[4] = count[0]* count[3] (根結點爲1,左子樹爲空,右子樹有2,3,4三個數字繼續生成子樹,所以爲count[3])+ count[1]* count[2] (根結點爲2)+count[2]* count[1] (根結點爲3)+count[3]*count[0] (根結點爲4);
算法複雜度:O(n^2)
代碼實現如下:

class Solution {
public:
    int numTrees(int n) {
        vector<int> count(n+1, 0);
        count[0] = count[1] = 1;
        for(int i = 2; i <= n; i++) {
            for(int j = 1; j <= i; j++)
                count[i] +=count[i-j]*count[j-1];
        }
        return count[n];
    }
};
發佈了37 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章