LeetCode刷题 Day41

131 阅读2分钟

LeetCode刷题 Day41

343. Integer Break

Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

Return the maximum product you can get.

 Example 1:

Input: n = 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.

Example 2:

Input: n = 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

思路:

  1. dp index和value的意义: index代表要拆分的数, value代表max product value
  2. 递推公式, 可以分为两种情况考虑:
    1. 用j (1 <= j < i - 1) 去乘以 dp[i - j], dp[i - j]就是 i - j的位置上的max product value
    2. 用j 直接 乘以 i - j。
  3. dp初始化, 根据题意i = 0,1是没有意义的, 所以可以直接从2开始。dp[2] = 1。之后的dp value可以直接设定为1.
  4. dp 遍历顺序, 从左至右。
  5. 举例推导dp数组

image.png

代码:

var integerBreak = function(n) {
    let dp = Array(n + 1).fill(1);
    dp[2] = 1;
    for (let i = 3; i <= n; i++) {
        for (let j = 1; j < i - 1; j++) {
            dp[i] = Math.max(dp[i], dp[i - j] * j, (i - j) * j);
        }
    }

    return dp[n];
};

时间复杂度: O(n2),空间复杂度: O(n)


96. Unique Binary Search Trees

Given an integer n, return the number of structurally unique BST' s (binary search trees) which has exactly n nodes of unique values from 1 to n.

Example 1:

Input: n = 3
Output: 5

Example 2:

Input: n = 1
Output: 1

思路: 这道题可以拆分成以i (1 <= i <= n)为头结点时搜索树数量之和 比如: dp[3] = dp[2] * dp[0] + dp[1] * dp[1] + dp[0] * dp[2]

  1. dp index和value: 代表i个节点时的BST数量
  2. dp公式推导: dp[i] = dp[j - 1] * dp[i - j];
  3. dp初始化: dp[0] = 1, 空节点也可以看成是二叉树
  4. 遍历顺序: 从左到右,二层循环
        for (let i = 1; i <= n; i++) {
            for (let j = 1; j <= i; j++)
        }
  1. 举例推导:

image.png

代码:

var numTrees = function(n) {
    let dp = Array(n + 1).fill(0);
    dp[0] = 1;

    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= i; j++) {            
            dp[i] += dp[j - 1] * dp[i - j];
        }
    }

    return dp[n];
};

时间复杂度: O(n2), 空间复杂度: O(n)