zoukankan      html  css  js  c++  java
  • 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]
  • 相关阅读:
    AGC 015 E
    CF 1041 F. Ray in the tube
    AGC 005 D
    CF 348 D. Turtles
    2069: [POI2004]ZAW
    AGC 007 D
    zhengruioi 470 区间
    2653: middle
    Django 源码安装及使用
    Django MTV模型思想
  • 原文地址:https://www.cnblogs.com/shish/p/13307218.html
Copyright © 2011-2022 走看看