1049. 最后一块石头的重量 II - 力扣(LeetCode)
class Solution {
public int lastStoneWeightII(int[] stones) {
if(stones.length == 0){
return 0;
}
if(stones.length == 1){
return stones[0];
}
int sum = 0;
for(int i=0;i<stones.length;i++){
sum += stones[i];
}
int weight = sum / 2;
// int[][] dp = new int[stones.length][weight+1];
// for(int i=0;i<=weight;i++){
// if(i >= stones[0]){
// dp[0][i] = stones[0];
// }
// }
// for (int i=1;i<stones.length;i++){
// for (int j=1;j<=weight;j++){
// if(j>=stones[i]){
// dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-stones[i]] + stones[i]);
// }else{
// dp[i][j] = dp[i-1][j];
// }
// }
// }
// return sum - 2 * dp[stones.length-1][weight];
int[] dp = new int[weight+1];
for(int i=0;i<=weight;i++){
if(i>=stones[0]){
dp[i] = stones[0];
}
}
for(int i=1;i<stones.length;i++){
for (int j=weight;j>=stones[i];j--){
dp[j] = Math.max(dp[j],dp[j-stones[i]] +stones[i]);
}
}
return sum - 2*dp[weight];
}
}
494. 目标和 - 力扣(LeetCode)
class Solution {
public int findTargetSumWays(int[] nums, int target) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
if (sum < Math.abs(target) || (sum + target) % 2 != 0) {
return 0;
}
int weight = (sum + target) / 2;
int[][] dp = new int[nums.length][weight+1];
for(int i=0;i<=weight;i++){
if(nums[0] == i){
dp[0][i] = 1;
}
}
int zeroNum = 0;
for(int i=0;i<nums.length;i++){
if(nums[i] == 0){
zeroNum++;
}
dp[i][0] = (int)Math.pow(2,zeroNum);
}
for (int i=1;i<nums.length;i++){
for(int j=1;j<=weight;j++){
if(j>=nums[i]){
dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i]];
}else{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[nums.length-1][weight];
}
}
474. 一和零 - 力扣(LeetCode)
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i < strs.length; i++) {
int[] zeroOneNumCount = getZeroOneNumCount(strs[i]);
int zeroNum = zeroOneNumCount[0];
int oneNum = zeroOneNumCount[1];
for (int j = m; j >= zeroNum; j--) {
for (int k = n; k >= oneNum; k--) {
dp[j][k] = Math.max(dp[j][k], dp[j - zeroNum][k - oneNum] + 1);
}
}
}
return dp[m][n];
}
private int[] getZeroOneNumCount(String str) {
int[] zeroOneNumCount = new int[2];
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '0') {
zeroOneNumCount[0]++;
} else {
zeroOneNumCount[1]++;
}
}
return zeroOneNumCount;
}
}