1049. 最后一块石头的重量 II
- 刷题
https://leetcode.cn/problems/last-stone-weight-ii/description/
- 文章讲解
https://programmercarl.com/1049.%E6%9C%80%E5%90%8E%E4%B8%80%E5%9D%97%E7%9F%B3%E5%A4%B4%E7%9A%84%E9%87%8D%E9%87%8FII.html
- 视频讲解
https://www.bilibili.com/video/BV14M411C7oV/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解:
// 一维数组版本 class Solution { public int lastStoneWeightII(int[] stones) { int sum = 0; for (int i : stones) { sum += i; } int target = sum >> 1; //初始化dp数组 int[] dp = new int[target + 1]; for (int i = 0; i < stones.length; i++) { //采用倒序 for (int j = target; j >= stones[i]; j--) { //两种情况,要么放,要么不放 dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]); } } return sum - 2 * dp[target]; } }
494. 目标和
- 刷题
https://leetcode.cn/problems/target-sum/description/
- 文章讲解
https://programmercarl.com/0494.%E7%9B%AE%E6%A0%87%E5%92%8C.html
- 视频讲解
https://www.bilibili.com/video/BV1o8411j73x/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解:
class Solution {
public int findTargetSumWays(int[] nums, int target) {
int sum = 0;
for (int i = 0; i < nums.length; i++) sum += nums[i];
//如果target过大 sum将无法满足
if ( target < 0 && sum < -target) return 0;
if ((target + sum) % 2 != 0) return 0;
int size = (target + sum) / 2;
if(size < 0) size = -size;
int[] dp = new int[size + 1];
dp[0] = 1;
for (int i = 0; i < nums.length; i++) {
for (int j = size; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]];
}
}
return dp[size];
}
}
474.一和零
- 刷题
https://leetcode.cn/problems/ones-and-zeroes/description/
- 文章讲解
https://programmercarl.com/0474.%E4%B8%80%E5%92%8C%E9%9B%B6.html
- 视频讲解
https://www.bilibili.com/video/BV1rW4y1x7ZQ/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解:
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
//dp[i][j]表示i个0和j个1时的最大子集
int[][] dp = new int[m + 1][n + 1];
int oneNum, zeroNum;
for (String str : strs) {
oneNum = 0;
zeroNum = 0;
for (char ch : str.toCharArray()) {
if (ch == '0') {
zeroNum++;
} else {
oneNum++;
}
}
//倒序遍历
for (int i = m; i >= zeroNum; i--) {
for (int j = n; j >= oneNum; j--) {
dp[i][j] = Math.max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1);
}
}
}
return dp[m][n];
}
}