算法训练营第43天|LeetCode 1049.最后一块石头的重量Ⅱ 494.目标和 474.一和零

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];
    }
};
相关推荐
望舒5132 分钟前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
C++ 老炮儿的技术栈18 分钟前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法
KYGALYX22 分钟前
逻辑回归详解
算法·机器学习·逻辑回归
铉铉这波能秀31 分钟前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.31 分钟前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
踢足球092934 分钟前
寒假打卡:2026-2-8
数据结构·算法
IT猿手44 分钟前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风1 小时前
SMU-ACM2026冬训周报3rd
算法
铉铉这波能秀1 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
晚霞的不甘1 小时前
Flutter for OpenHarmony 实现计算几何:Graham Scan 凸包算法的可视化演示
人工智能·算法·flutter·架构·开源·音视频