题目描述
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You have a collection of rods which can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.
Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.
Example 1:
Input: [1,2,3,6]
Output: 6
Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
Example 2:
Input: [1,2,3,4,5,6]
Output: 10
Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
Example 3:
Input: [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.
Note:
0 <= rods.length <= 20
1 <= rods[i] <= 1000
The sum of rods is at most 5000.
思路
动态规划。看了花花酱的题解。
确实,如果模拟这个过程的话,下一根棍子放在哪边,产生的新的高度差是子问题。
两边集合中棍子放置的顺序没有关系。
所以用高度差来表示状态,dp[i][h1] = s 表示前i根棍子安排好以后,高度差是h1的最高公共部分为s。那么,每一根棍子h2,可以对已有的高度差转移状态,dp[i-1][h1+h2] 和 dp[i-1][abs(h1-h2)] 。
代码
class Solution {
public:
int tallestBillboard(vector<int>& rods) {
int s = accumulate(rods.begin(), rods.end(), 0);
vector<int> dp(s+1, -1);
dp[0] = 0;
for (int h : rods) {
vector<int> cur(dp);
for (int i=0; i<=s; ++i) {
if (cur[i] < 0) continue;
if (i+h <= s) dp[i+h] = max(dp[i+h], cur[i]);
dp[abs(i-h)] = max(dp[abs(i-h)], cur[i]+min(i, h));
}
}
return dp[0];
}
};
好难。。。
今天也感觉脑子像锈住了。不想转。
磨蹭半天,写了一道题。