Algorithm question check-in day41-Dynamic programming | 343. Integer splitting, 96. Different binary search trees

343. Integer split - LeetCode

Status: AC after checking the train of thought.

1. dp[i] represents the maximum split product at the i-th location;

2. dp[i] = max(dp[i], (i-j)*j, dp[i-j]*j);

3. dp[0], dp[1] has no meaning of initialization, dp[2] = 1;

4. for(i = 3; i < n+1; ++i){ for(j = 1; j < i-1; ++j) { 转移方程 }};

5. You can pass after giving some examples.

Time complexity O(n^2), space complexity O(n), the code is as follows:

class Solution {
public:
    int integerBreak(int n) {
        vector<int> dp(n+1);
        dp[2] = 1;
        for(int i = 3; i < n+1; ++i){
            for(int j = 1; j < i-1; ++j){
                dp[i] = max(dp[i], max((i-j)*j, dp[i-j]*j));
            }
        }
        return dp[n];
    }
};

96. Different binary search trees - LeetCode

Status: AC after checking the train of thought.

1. dp[i] represents the number of binary trees at the i-th location;

2. dp[i] = dp[i] + dp[j-1]*dp[i-j];

3. dp[0] = 1, j-1 is the number of left subtree nodes with j as the head node, ij is the number of right subtree nodes with j as the head node;

4. for(i = 1; i < n+1; ++i){ for(j = 1; j < i+1; ++j) { 转移方程 }};

5. You can pass after giving some examples.

Time complexity O(n^2), space complexity O(n), the code is as follows:

class Solution {
public:
    int numTrees(int n) {
        vector<int> dp(n+1);
        dp[0] = 1;
        for(int i = 1; i < n+1; ++i){
            for(int j = 1; j < i+1; ++j){
                dp[i] += dp[j-1]*dp[i-j];
            }
        }
        return dp[n];
    }
};

Guess you like

Origin blog.csdn.net/qq_40395888/article/details/132408141