LeetCode check-in day41--different binary search trees, integer split


knowledge summary

In dynamic programming, the most important thing is to find the recursive formula, which is a bit like the math problem of finding the law


Leetcode 96. Different Binary Search Trees

topic link

topic description

Given an integer n, how many binary search trees are there that consist of exactly n nodes and whose node values ​​vary from 1 to n? Returns the number of binary search trees that satisfy the meaning of the question.
insert image description here

code description

The recursive formula can be understood as
finding a binary search tree with N nodes

dp[N]  = dp[0] * dp[N-1] + dp[1] *  dp[N-2] +... + dp[N-1] * dp[0] 

After finding the recursive formula, it is easy to write

class Solution {
    
    
    public int numTrees(int n) {
    
    
        int[] dp = new int[n+1];
        dp[0] = 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];
    }
}

Leetcode 343. Integer Split

topic link

topic description

Given a positive integer n, split it into sums of k positive integers ( k >= 2 ) and maximize the product of these integers.

Return the largest product you can get.

insert image description here

code description

The method I came up with is easier to understand:
To split the number N,
suppose N = 5,
a = 2, b = 3

dp[2] = 1, dp[3] = 2
dp[5] = max(dp[2], 2) * max(dp[3], 3)
and then find the maximum value of dp[5] in turn

class Solution {
    
    
    public int integerBreak(int n) {
    
    
        int[] dp = new int[n+1];
        dp[0] = 1;
        dp[1] = 1;
        for(int i = 2; i <= n; i++){
    
    
            for(int j = 1; j <= i / 2 ; j++){
    
    
                int l = Math.max(j, dp[j]);
                int r = Math.max(i-j, dp[i-j]);
                dp[i] = Math.max(l*r, dp[i]);
            }
        }
        return dp[n];
    }
}

Guess you like

Origin blog.csdn.net/weixin_45872648/article/details/131295396