1872. Minimum Cost to Connect Sticks
You have some sticks with positive integer lengths.
You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. You perform this action until there is one stick remaining.
Return the minimum cost of connecting all the given sticks into one stick in this way.
Example
Example 1:
Input:
[2,4,3]
Output: 14
Explanation: First connect 2 and 3 to 5 and cost 5; then connect 5 and 4 to 9; total cost is 14
Example 2:
Input:
[1,8,3,5]
Output: 30
Notice
1≤sticks.length≤10^4
1≤sticks[i]≤10^4
解法1:用minHeap
注意这题是基于贪婪法。但光排序sticks数组是不行的,因为connected之后的新stick也算一个stick。
class Solution {
public:
/**
* @param sticks: the length of sticks
* @return: Minimum Cost to Connect Sticks
*/
int MinimumCost(vector<int> &sticks) {
int len = sticks.size();
int sum = 0;
priority_queue<int, vector<int>, greater<int>> minHeap(sticks.begin(), sticks.end());
while(minHeap.size() > 1) {
int cost = 0;
cost += minHeap.top(); minHeap.pop();
cost += minHeap.top(); minHeap.pop();
minHeap.push(cost);
sum += cost;
}
return sum;
}
};
二刷: 不如上面的版本好。
class Solution {
public:
/**
* @param sticks: the length of sticks
* @return: Minimum Cost to Connect Sticks
*/
int minimumCost(vector<int> &sticks) {
priority_queue<int, vector<int>, greater<int>> minHeap;
for (auto stick : sticks) {
minHeap.push(stick);
}
int res = 0;
while (!minHeap.empty()) {
int top1 = minHeap.top(), top2 = 0;
minHeap.pop();
if (!minHeap.empty()) {
top2 = minHeap.top();
minHeap.pop();
int sum = top1 + top2;
res += sum;
if (minHeap.empty()) return res;
minHeap.push(sum);
} else {
return res + top1;
}
}
return res;
}
};
本文介绍了一种基于贪婪算法的解决方案,旨在找到将多个具有正整数长度的木棒连接成一根木棒所需的最小成本。通过使用最小堆数据结构,可以有效地找到并合并最短的两根木棒,直至只剩一根木棒。
1183

被折叠的 条评论
为什么被折叠?



