1049 最後一塊石頭的重量II
class Solution {
public:
int lastStoneWeightII(vector
int sum = 0;
for(int &it : stones)
{
sum += it;
}
int target = sum / 2;
vector
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 目標和
class Solution {
public:
int findTargetSumWays(vector
int sum = 0;
for(int &it : nums)
{
sum += it;
}
if (abs(target) > sum) return 0; // 此時沒有方案
if ((target + sum) % 2 == 1) return 0;
int left = (target + sum) / 2;
vector
dp[0] = 1;
for(int i = 0; i < nums.size(); ++i)
{
for(int j = left; j >= nums[i]; j--)
{
dp[j] += dp[j - nums[i]];
}
}
return dp[left];
}
};
474 一和零
class Solution {
public:
int findMaxForm(vector
vector<vector
dp[0][0] = 0;
for(string &str : strs)
{
int x = 0;
int y = 0;
for(char &ch : str)
{
if(ch == '0')
{
++x;
}
else
{
++y;
}
}
for(int i = m; i >= x; --i)
{
for(int j = n; j >= y; --j)
{
dp[i][j] = max(dp[i][j], dp[i-x][j-y] + 1);
}
}
}
return dp[m][n];
}
};