1049. 最后一块石头的重量 II
- 尽可能相同重量两堆石头相减,剩下的 sum-dp[sum/2] 再减去dp[sum/2]就是最终剩下的。
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
std::vector<int> dp(15001, 0);
int sum = 0;
for (int i = 0; i < stones.size(); i++) sum += stones[i];
int target = sum / 2;
for (int i = 0; i < stones.size(); ++i) {
for (int j = target; j >= stones[i] ; --j) {
dp[j] = max(dp[j], dp[j-stones[i]]+stones[i]);
}
}
return sum - dp[target]-dp[target];
}
};
494. 目标和
更新
dp[j] += dp[j - nums[i]];
474.一和零
- 二维数组的初始化
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int>> dp(m+1, vector<int>(n+1,0));
for (const auto &str: strs) {
int zeroCnt = 0, oneCnt = 0;
for (const auto &letter: str) {
if (letter == '0') ++zeroCnt;
else ++oneCnt;
}
for (int i = m; i >=zeroCnt ; --i) {
for (int j = n; j >= oneCnt; --j) {
dp[i][j] = max(dp[i][j], dp[i-zeroCnt][j-oneCnt]+1);
}
}
}
return dp[m][n];
}
};