原題地址:https://oj.leetcode.com/problems/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
解題思路:這題從數學上講,其實是卡特蘭數。不過我們顯然不從數學上來解決這個問題。這題是求二叉樹的棵數。這里有個解題技巧:一般來說求數量,要首先想到使用動態規划(dp),而如果是像下一題的要求,不只是數量,還要把所有的樹都枚舉出來,就要使用dfs(深度優先搜索)來遍歷決策樹了。
那么這道題是使用動態規划來解決的。那么如何去求這個問題的狀態轉移方程呢?其實大部分動態規划的難點都是求狀態轉移方程。n=0時,為空樹,那么dp[0]=1; n=1時,顯然也是1,dp[1]=1;n=2時,dp[2]=2; 對於n>2時,dp[n]=dp[0]*dp[n-1]+dp[1]*dp[n-2]+......+dp[n-1]*dp[0];這不就是卡特蘭數的定義嗎?編程很容易實現。
代碼:
class Solution: # @return an integer def numTrees(self, n): dp = [1, 1, 2] if n <= 2: return dp[n] else: dp += [0 for i in range(n-2)] for i in range(3, n + 1): for j in range(1, i+1): dp[i] += dp[j-1] * dp[i-j] return dp[n]