LeetCode 1049.最后一块石头的重量Ⅱ
题目链接:
LeetCode 1049.最后一块石头的重量Ⅱ
代码:
cpp
复制代码
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int sum = 0;
int size = stones.size();
for(int i=0;i<size;i++){
sum += stones[i];
}
int target = sum/2;
vector<int>dp(3010,0);
for(int i = 0;i<size;i++){
for(int j=target;j>=stones[i];j--){
dp[j]=max(dp[j],dp[j-stones[i]]+stones[i]);
}
}
int temp = sum-dp[target];
return abs(temp-dp[target]);
}
};
LeetCode 494.目标和
题目链接:
LeetCode 494.目标和
代码:
cpp
复制代码
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int size = nums.size();
int sum = 0;
for (int i = 0; i < nums.size(); i++) sum += nums[i];
if (abs(target) > sum) return 0; // 此时没有方案
if ((target + sum) % 2 == 1) return 0; // 此时没有方案
int temp = (sum+target)/2;
vector<int>dp(temp+1,0);
dp[0]=1;
for (int i = 0; i < nums.size(); i++) {
for (int j = temp; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]];
}
}
return dp[temp];
}
};
LeetCode 474.一和零
题目链接:
LeetCode 474.一和零
代码:
cpp
复制代码
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int>>dp(m+1,vector<int>(n+1,0));
for(string str:strs){
int x=0,y=0;
for(char ch:str){
if(ch=='1')y++;
if(ch=='0')x++;
}
for(int i=m;i>=x;i--){
for(int j=n;j>=y;j--){
dp[i][j] = max(dp[i-x][j-y]+1,dp[i][j]);
}
}
}
return dp[m][n];
}
};