鱼C论坛

 找回密码
 立即注册
查看: 2184|回复: 0

[技术交流] C++刷LeetCode(1130. 叶值的最小代价生成树)【递减栈】【数学】

[复制链接]
发表于 2021-1-5 12:49:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 给你一个正整数数组 arr,考虑所有满足以下条件的二叉树:

  2. 每个节点都有 0 个或是 2 个子节点。
  3. 数组 arr 中的值与树的中序遍历中每个叶节点的值一一对应。(知识回顾:如果一个节点有 0 个子节点,那么该节点为叶节点。)
  4. 每个非叶节点的值等于其左子树和右子树中叶节点的最大值的乘积。
  5. 在所有这样的二叉树中,返回每个非叶节点的值的最小可能总和。这个和的值是一个 32 位整数。

  6.  

  7. 示例:

  8. 输入:arr = [6,2,4]
  9. 输出:32
  10. 解释:
  11. 有两种可能的树,第一种的非叶节点的总和为 36,第二种非叶节点的总和为 32。

  12.     24            24
  13.    /  \          /  \
  14.   12   4        6    8
  15. /  \               / \
  16. 6    2             2   4
  17.  

  18. 提示:

  19. 2 <= arr.length <= 40
  20. 1 <= arr[i] <= 15
  21. 答案保证是一个 32 位带符号整数,即小于&#160;2^31。

  22. 来源:力扣(LeetCode)
  23. 链接:https://leetcode-cn.com/problems/minimum-cost-tree-from-leaf-values
  24. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码



  1. class Solution {
  2. public:
  3.     int mctFromLeafValues(vector<int>& arr) {
  4.         int res = 0;
  5.         stack<int>store;
  6.         store.push(INT_MAX);
  7.         for(auto cha : arr){
  8.             while(cha > store.top()){
  9.                 int temp = store.top();
  10.                 store.pop();
  11.                 res += temp * min(store.top(), cha);
  12.             }
  13.             store.push(cha);
  14.         }
  15.         while(store.size() > 2){
  16.             int temp = store.top();
  17.             store.pop();
  18.             res += temp * store.top();
  19.         }
  20.         return res;
  21.     }
  22. };
复制代码



参考链接:https://leetcode-cn.com/problems ... zhan-by-crossing-2/

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-3 05:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表