大佬教程收集整理的这篇文章主要介绍了[Swift]LeetCode1130. 叶值的最小代价生成树 | Minimum Cost Tree From Leaf Values,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公众号:山青咏芝(shanqingyongzhi)
?博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
?GitHub地址:https://github.com/strengthen/LeetCode
?原文地址:https://www.cnblogs.com/strengthen/p/11223721.html
?如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
?原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given an array arr
of positive Integers,consider all binary trees such that:
arr
correspond to the values of each leaf in an in-order traversal of the tree. (Recall that a node is a leaf if and only if it has 0 children.)
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.
Example 1:
Input: arr = [6,2,4] Output: 32 Explanation: There are two possible trees. The first has non-leaf node sum 36,and the second has non-leaf node sum 32. 24 24 / \ / 12 4 6 8 / \ / 6 2 2 4
ConsTraints:
2 <= arr.length <= 40
1 <= arr[i] <= 15
2^31
).arr
中的值与树的中序遍历中每个叶节点的值一一对应。(知识回顾:如果一个节点有 0 个子节点,那么该节点为叶节点。)在所有这样的二叉树中,返回每个非叶节点的值的最小可能总和。这个和的值是一个 32 位整数。
示例:
输入:arr = [6,4] 输出:32 解释: 有两种可能的树,第一种的非叶节点的总和为 36,第二种非叶节点的总和为 32。 24 24 / \ / 12 4 6 8 / \ / 6 2 2 4
提示:
2 <= arr.length <= 40
1 <= arr[i] <= 15
2^31
。1 class Solution { 2 func mctFromLeafValues(_ arr: [Int]) -> Int { 3 var dp:[[Int]] = [[Int]](repeaTing:[Int](repeaTing:@H_404_110@0,count:@H_404_110@45),count:@H_404_110@45) 4 var maxn:[[Int]] = [[Int]](repeaTing:[Int](repeaTing:@H_404_110@0,count:@H_404_110@45) 5 var n:Int = arr.count 6 for i in @H_404_110@0..<n 7 { 8 maxn[i][i] = arr[i] 9 for j in (i + @H_404_110@1)..<n 10 { 11 maxn[i][j] = max(maxn[i][j - @H_404_110@1],arr[j]) 12 } 13 } 14 for d in @H_404_110@2...n 15 { 16 var i:Int = @H_404_110@0 17 while(i + d - @H_404_110@1 < n) 18 { 19 var j:Int = i + d - @H_404_110@1 20 dp[i][j] = (@H_404_110@1<<@H_404_110@60) 21 for k in i..<j 22 { 23 dp[i][j] = min(dp[i][j],maxn[i][k] * maxn[k+@H_404_110@1][j] + dp[i][k] + dp[k + @H_404_110@1][j]) 24 } 25 i += @H_404_110@1 26 } 27 } 28 return (dp[@H_404_110@0][n - @H_404_110@1]) 29 } 30 }
以上是大佬教程为你收集整理的[Swift]LeetCode1130. 叶值的最小代价生成树 | Minimum Cost Tree From Leaf Values全部内容,希望文章能够帮你解决[Swift]LeetCode1130. 叶值的最小代价生成树 | Minimum Cost Tree From Leaf Values所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。