1130. Minimum Cost Tree From Leaf Values(DP)

Given an array arr of positive integers, consider all binary trees such that:

  • Each node has either 0 or 2 children;
  • The values of arr correspond to the values of each leaf in an in-order traversal of the tree.
  • The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively.

Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.

A node is a leaf if and only if it has zero children.

This is a typical interval DP question. The special place of this problem is a node's value depends on its leaf node's value.

So, we first store all the interval's maximum leaf node and then do a normal interval dp.

dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + maxleaf[i][k] * maxleaf[k + 1][j])

class Solution {
public:
    int mctFromLeafValues(vector& arr) {
        //calculate the maxi leaf in every interval
        int n = arr.size();
        vector> maxLeaf(n, vector(n, 0));
        for(int i = 0; i < n; i++)maxLeaf[i][i] = arr[i];
        for(int i = 0; i < n; i++){
            for(int j = i + 1; j < n; j++){
                maxLeaf[i][j] = max(maxLeaf[i][j - 1], arr[j]);
            }
        }
        vector> dp(n, vector(n, 0));
        for(int len = 1; len < n; len++){
            for(int j = 0; j < n - len; j++){
                int end = j + len;
                dp[j][end] = 1e8;
                for(int k = j; k < end; k++){
                    dp[j][end] = min(dp[j][k] + dp[k + 1][end] + maxLeaf[j][k] * maxLeaf[k + 1][end], dp[j][end]);
                }
            }
        }
        return dp[0][n - 1];
    }
};

你可能感兴趣的:(動態規劃,Leetcode,算法,c++,动态规划)