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

直接想到遞歸,給定i作爲根,左右子樹還有i-1,n-i個值,遞歸進行計算,累加起來得到結果:

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