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.
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<Solution>
這題就是要專有的公式解,叫做 Catalan Number
Catalan Number 除了可以來計算由 1 到 n 個正整數組成的 unique BST 外
還有其他題目也可以應用,詳情請看連結
主要要把這個公式記下來
code 如下
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int numTrees(int n) { | |
//> dynamic programming | |
int dp[n+1] = {1}; | |
for(int i = 1; i <= n; i++) { | |
for(int j = 0; j < i; j++) { | |
dp[i] += dp[j] * dp[i - 1 - j]; | |
} | |
} | |
return dp[n]; | |
} | |
}; |
沒有留言:
張貼留言