1. 程式人生 > 實用技巧 >2020.7.15 刷

2020.7.15 刷

96. 不同的二叉搜尋樹

自己用dp寫的哈哈哈不是很整潔

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

貼個思路卡特蘭數

class Solution {
    public int numTrees(int n) {
        int[] dp = new int[n+1];
        dp[
0] = 1; dp[1] = 1; for(int i = 2; i < n + 1; i++) for(int j = 1; j < i + 1; j++) dp[i] += dp[j-1] * dp[i-j]; return dp[n]; } } 作者:guanpengchn 連結:https://leetcode-cn.com/problems/unique-binary-search-trees/solution/hua-jie-suan-fa-96-bu-tong-de-er-cha-sou-suo-shu-b/
來源:力扣(LeetCode) 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

在貼個python程式碼

class Solution:
    def numTrees(self, n: int) -> int:
        dp = [1, 1, 2]
        for i in range (3, n + 1):
            res = 0
            for j in range (1, (int)(i/2 + 1)):
                res += dp[j - 1] * dp[i - j]
            res *= 2
            if i % 2 == 1:
                res += dp[(int)((i-1)/ 2)] ** 2
            dp.append(res)
        return dp[n]