代码随想录算法训练营第四十一天|动态规划part03|● 343. 整数拆分 ● 96.不同的二叉搜索树

●  343. 整数拆分 Integer Break - LeetCode

dp[i] 对i进行拆分,拆分后得到的最大乘积就是dp[i]

j * (i - j) //j是1到j

j * dp[i - j]//三个数或以上

dp[0] = 0;

dp[1] = 0;

dp[2] = 1;

for (int i = 3; i <= n; i++)

        for (int j = 1; j <= i/2; j++) //拆成尽可能相似的数

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

class Solution {
    public int integerBreak(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 0;
        dp[2] = 1;

        for (int i = 3; i <= n; i++) {
            for (int j = 1; j <= i/2; j++) {
                dp[i] = Math.max(dp[i], Math.max(j * (i - j), j * dp[i - j]));
            }
        }
        return dp[n];
    }
}

●  96.不同的二叉搜索树 Unique Binary Search Trees - LeetCode

dp[i]种不同的二叉树

dp[i]以i为头节点的情况,用j来枚举,左子树有j-1个,右边都比j大,右边有i-j个

dp[i] += dp[j - 1] * dp[i - j]

dp[0] = 1;

dp[1] = 1;

遍历顺序:dp[i] 依赖前面的,从小到大

for (int i = 1; i <= n; i++)

        for (int j = 1; j <= i; j++)

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

打印dp数组

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; i++) {
            for (int j = 1; j <= i; j++) {
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];
    }
}

你可能感兴趣的:(代码随想录算法训练营,算法,动态规划,leetcode,数据结构)