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<int>& arr) {
        //calculate the maxi leaf in every interval
        int n = arr.size();
        vector<vector<int>> maxLeaf(n, vector<int>(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<vector<int>> dp(n, vector<int>(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];
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值